개념


I/O (입출력) - 입력 , 출력 / 두 대상 간의 데이터를 주고 받는 것



Stream -  데이터를 운반 하는데 사용되는 연결통로

         -  연속적인 흐름

         -  입출력을 동시에 수행하려면, 2개의 스트림이 필요하다.





간단한 코드지만 아래의 코드를 살펴보자.


import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;


public class FileTest {


public static void main(String args[]) {


FileInputStream fis = null;

FileOutputStream fos = null;


try {

fis = new FileInputStream("log.txt");

fos = new FileOutputStream("back_log.txt");


int data = 0;

byte[] b = new byte[1];


while ((data = fis.read(b)) != -1) {

System.out.println(data);

fos.write(b);

fos.flush();

}


} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

System.out.println("File Not found");

e.printStackTrace();

} catch (IOException e1) {

// TODO Auto-generated catch block

System.out.println("File Not found");

e1.printStackTrace();

}finally {

if(fos!=null) {

try {

fos.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(fis!=null) {

try {

fis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}

}




네트워크, 특히 서버에서 예외 처리와 close() 메소드는 매우 중요하다.


만일 close() 메소드를 try 문에 포함시켜서 한다고 가정하자. 


서버에서 예외가 발생하면 스트림은 닫히지 않고 메모리 누수가 발생할 요소가 있다.


꼼꼼한 예외처리와 try catch, finally 는 자바 네트워크에서 중요한 요소이다.





스트림의 종류


바이트 기반 스트림 


  - inputstream , outputstream


  - 1byte 단위




 문자 기반 스트림

 

  - reader, writer

  -  문자 단위












+ Recent posts