FileStream, 파일스트림
FileStream, 파일스트림
: 파일 입출력에 사용되는 클래스
: 1. 바이트 단위 - FileInputStream, FileOutputStream
: 2. 문자열 단위 - FileReader, FileWriter
※ 스트림이란?
: 일련의 연속된 데이터의 흐름
: 자바프로그램과 외부장치 사이의 데이터 교환을 위한 처리 방식
: 추상화, 실제 장치와 상관없이 공통된 접근 방식을 제공한다.
여기서는 파일 입출력 스트림만 다루고 있으며 다른 입출력 스트림에 대한 사항은 다음 링크를 참조
Link - I/O Stream, 입출력 스트림
※ 인코딩, Encoding
: 응용프로그램의 데이터를 스트림(Stream)형식으로 변환시켜
: 보조기억장치나 네트워크상에서 사용가능한 형태로 변환하는 작업
1) ANSI(미국표준) : 한글 2byte, 영어(숫자) 1byte
2) EUC-KR : 한글 2byte, 영어(숫자) 1byte
3) UTF-8 : 한글 3byte, 영어(숫자) 1byte
4) UTF-16 : 한글 2byte, 영어(숫자) 2byte
Link - 아스키코드표
1. FileIntputstream/FileOutputStream
■ FileOutputStream
: 파일 출력 스트림
1) 스트림 열기
1 2 3 4 | FileOutputStream fos = new FileOutputStream( "d:\\web\\data.txt" [, true | false ]); // true : Append, 이어쓰기 // false : Create, 기존 내용에 덮어쓰기 // 기본값 : false |
2) 조작
1 2 3 | fos.write( 97 ); //byte코드 값에 해당하는 문자(character)를 파일에 출력 fos.write( 98 ); fos.write( 99 ); |
3) 스트림 닫기
1 2 | fos.close(); //실행 후 data.txt 파일을 열어보면 abc가 적혀있다. |
4) 응용
1 2 3 4 5 6 7 8 9 | String txt = "hello! Fine and strong day! if you ask my name, im waldo!" ; //입력할 문자열 for ( int i = 0 ; i < txt.length(); i++) //문자열의 길이만큼 { char c = txt.charAt(i); //문자로 형변환 후 fos.write(( int ) c); //출력한다. } fos.close(); |
바이트배열을 활용하면 다음과 같다.
1 2 3 4 5 6 7 8 | FileOutputStream fos = new FileOutputStream( "d:\\web\\data.txt" , false ); String txt = "hello! Fine and strong day! if you ask my name, im waldo!" ; byte [] bs = txt.getBytes(); //문자열을 바이트 배열에 할당 fos.write(bs); //출력한다. fos.close(); |
■ FileInputStream
: 파일 입력 스트림
위에서 입력한 파일을 읽어서 콘솔에 출력해보자.
1) 스트림 열기
1 2 3 4 | File dir = new File( "d:\\data.txt" ); FileInputStream fis = new FileInputStream(dir); //혹은 FileInputStream fis = new FileInputStream( "d:\\web\\data.txt" ); |
2) 조작
1 2 3 4 5 6 7 8 | int b; while ((b = fis.read()) != - 1 ) //read()는 더 이상 읽을것이 없을 때 -1을 리턴한다. -1까지 루프 { System.out.print(( char )b); //스트림이 읽은 바이트코드를 문자로 변환하여 출력 } → hello! Fine and strong day! if you ask my name, im waldo! |
3) 스트림 닫기
1 | fis.close(); |
※ 주의
이렇게 바이트로 읽어온 문자열은 1바이트 문자코드 방식에만 해당된다.
즉, 어떤 인코딩이던 2바이트가 넘어가는 한글은 읽을 수 없다.
2. FileReader/FileWriter
: stream이 바이트단위로만 읽고 쓰기가 가능한것을 개량한 클래스
: 한글 처리가 가능하다.
■ FileWriter
1) 스트림 열기
1 2 3 4 | FileWriter fw = new FileWriter( "d:\\web\\data.txt" [, true | false ]); //true : Append, 이어쓰기 //false : Create, 기존 내용에 덮어쓰기 //기본값 : false |
2) 조작
1 2 | String txt = "You just activated \r\nMY TRAP CARD" ; fw.write(txt); |
3) 스트림 닫기
1 | fw.close(); |
한 눈에 보이듯이 바이트 처리를 알아서 하도록 설계되어있는 클래스이기 때문에 코드가 굉장히 간결하다.
가장 중요한 점은 stream에선 불가능했던 한글 처리가 가능하다는 것이다.
1 2 3 | FileWriter fw = new FileWriter( "D:\\web\\data2.txt" , false ); fw.write( "붑밥붑밥붑밥바 붑바밥붑밥붑밥바" ); fw.close(); |
■ FileReader
FileReader는 InputStream과 사용방법이 동일하다.
1) 스트림 열기
1 2 3 4 | String dir = "D:\\web\\data2.txt" ; FileReader fr = new FileReader(dir); //혹은 FileReader fr = new FileReader( "D:\\web\\data2.txt" ); |
2) 조작
1 2 3 4 5 | int b; while ((b = fr.read()) != - 1 ) //파일 내용의 길이만큼 루프 { System.out.print(( char )b); //읽어온 바이트코드를 문자로 변환. 출력 } |
3) 스트림 닫기
1 | fr.close(); |
FileReader 역시 stream에선 불가능했던 한글 처리가 가능하다.
3. BufferedReader/BufferedWriter
: Reader와 Writer를 개량한 클래스
: 기존 입출력 클래스보다 속도가 빠르다.
■ BufferedWriter
1 2 3 4 5 6 7 8 9 | BufferedWriter bw = new BufferedWriter( new FileWriter( "D:\\web\\data2.txt" )); bw.write( "버퍼드리더를 활용한 \r\n파일출력" ); bw.write( "줄바꿈" ); bw.newLine(); //"\r\n" bw.write( "줄바꼈지?" ); bw.flush(); bw.close(); |
BufferedWriter 의 경우 출력을 바로 하는것이 아니라 버퍼를 비울 때 출력한다.
flush() 메서드는 버퍼를 비우는 함수. flush()를 하지 않으면 출력은 처리되지 않는다.
※ close는 자동으로 버퍼를 비운다. 즉 스트림을 닫기만 해도 flush()는 생략할 수 있다.
■ BufferedReader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | String path = "D:\\web\\data2.txt" ; BufferedReader reader = new BufferedReader( new FileReader(path)); readLine() String txt; while ((txt = reader.readLine()) != null ) //읽을게 없으면 null 리턴 { System.out.println(txt); } reader.close(); read() int b; while ((b = reader.read()) != - 1 ) { System.out.print(( char )b); } reader.close(); |
4. BufferedFileStream
■ BufferedFileStream을 이용한 파일의 바이너리코드를 읽어와 다른 파일에 그대로 쓰기(복사)
1. 스트림 열기
1 2 3 | //FileStream FileInputStream is = new FileInputStream( "D:\\AAA\\test.zip" ); //읽어올 파일 FileOutputStream os = new FileOutputStream( "D:\\AAA\\test_2.zip" ); //출력할 파일 |
1 2 3 | //BufferedStream : FileStream보다 속도가 빠르다. BufferedInputStream is = new BufferedInputStream( new FileInputStream( "D:\\web\\.zip" )); BufferedOutputStream os = new BufferedOutputStream( new FileOutputStream( "D:\\AAA\\test_2.zip" )); |
2. 조작과 스트림 닫기
1 2 3 4 5 6 7 8 | while ((c = is.read()) != - 1 ) { os.write(c); len++; //복사크기 } System.out.printf( "총 %,d바이트 복사됨\n" , len); bis.close(); bos.close(); |
* FileStream이나 BufferedStream 모두 한글 깨짐없이 복사가능.