프로그래밍/자바

자바 파일 입출력 과 입출력 스트림

밍구몬 2019. 2. 27. 09:50

자바에는 바이트 스트림과 문자 스트림이 존재한다.

 

바이트 스트림

 

바이트 스트림은 입출력되는 바이트의 바이너리 값을 있는 그대로 처리한다. 그러므로 스트림에 들어오는 데이터가 문자이든 단순 바이너리 정보이든 상관없이 처리할 수 있다.

문자는 물론 이미지나 오디오 같은 파일도 읽을 수 있다.

 

[ 바이트 스트림 계층 구조 ]

 

바이트 스트림 파일 읽고 쓰기 예제

 

import java.io.IOException;

import java.io.FileInputStream;

import java.io.FileOutputStream;

 

 

public class test{

public static void main(String[] args) {

 

try {

FileOutputStream out = new FileOutputStream("D:\\test.txt");

FileInputStream in = new FileInputStream("D:\\test.txt");

 

String str = "stream test";

byte[] b = str.getBytes(); // 문자를 바이트로 변환

 

out.write(b); //파일 쓰기

 out.close();

 

int c;

while((c=in.read()) != -1){ //wile문으로 파일 읽기

                    System.out.print((char)c);

                }

 in.close();

 

} catch (Exception e) {

System.out.println(e);

}

 

}

}

 

 

문자 스트림

 

문자 스트림은 오직 문자만 다룬다. 문자가 아닌 바이트 정보가 들어오면 오류로 처리한다.

메모장으로 작성된 텍스트 파일이나 자바 소스 파일 같은 문자들로 이루어진 파일만 읽고 쓸 수 있다.

 

[ 문자 스트림 계층 구조 ]

 

문자 스트림 파일 읽고 쓰기 예제

 

import java.io.IOException;

import java.io.FileReader;

import java.io.FileWriter;

 

 

public class test{

public static void main(String[] args) {

 

try {

FileWriter fw = new FileWriter("D:\\test.txt");

FileReader fr = new FileReader("D:\\test.txt");

 

String str = "string stream test";

 

fw.write(str); //파일 쓰기

fw.close();

 

int c;

while((c=fr.read()) != -1){ //wile문으로 파일 읽기

            System.out.print((char)c);

         }

fr.close();

 

} catch (Exception e) {

System.out.println(e);

}

 

}

}