스트림(Stream) : 바이트스트림 - FileInputStream & FileOutputStream

sehwa!·2023년 9월 6일
0

Java

목록 보기
11/18

📌 스트림(Stream)
: 데이터가 이동하는 통로

분류

  • InputStream : 입력스트림
  • OutputStream : 출력스트림

데이터 종류에 따른 분류

  • 바이트스트림
  • 문자스트림

✅ 수업예문

1. FileInputSteam

파일로부터 바이너리 데이터를 읽어오기 위한 스트림클래스

💻 code

String filePath = "src\\fileInput_en.txt";
FileInputStream fis = null;
try {
	fis = new FileInputStream(filePath);
    int i = 0;
    while((i = fis.read()) != -1) {
    System.out.print((char)i);
} catch(FileNotFoundException e) {
	e.printStackTrace();
} catch(IOException e) {
	e.printStackTrace();
} finally {
	try{
    	if(fis != null) fis.close();
    } catch(IOException e) {}
}
  1. fis.read() 는 더이상 읽어올 데이터가 없으면 -1을 반환함
  2. 바이트스트림은 1byte씩 읽어출력하기 때문에 (char)i로 받았음
  3. fis.close()로 사용이 완료된 스트림을 닫음

📃 fileInput_en.txt

http://www.naver.com
http://www.google.com

👉 print

h104, t116, t116, p112, :58, /47, /47, w119, w119, w119, .46, n110, a97, v118, e101, r114, .46, c99, o111, m109, 
13, 
10, h104, t116, t116, p112, :58, /47, /47, w119, w119, w119, .46, g103, o111, o111, g103, l108, e101, .46, c99, o111, m109, 

2. FileOutputStream

파일의 바이너리 데이터를 출력하기 위한 스트림클래스

💻 code

String filePath = "src\\fileOutput.txt";
byte[] b = {'s', 't', 'r', 'e', 'a', 'm'};
int[] nums = {65, 66, 67, 68, 69, 70};
FileOutputStream fos = null;
try {
	fos = new FileOutputStream(filePath);
    fos.write(b);
    fos.write('\n');
    for(int i=0; i<nums.length; i++) {
    fos.write(nums[i]);
    }
} catch(IOException e) {
	e.printStackTrace();
} finally {
	try {
    	if(fos != null) fos.close();
    } catch(IOException e) {}
}

FileOutputStream(String name, boolean append)
: append가 true면 기존 데이터에 이어쓰기 false면 새로 쓰기
** append는 생략가능 (기본값 false)

👉 print 📃 fileOutput.txt

stream
ABCDEF

3. FileInputStream & FileOutputStream 으로 파일 복사하기

📃 fileInput.txt (복사용파일)

파일에서 바이트 단위로 읽어 들이는 FileInputStream
FileInputStream은 byte 기반 스트림 이다.

💻 code

String path = "src/fileInput.txt";
String destinationPath = "src/fileOutput.txt";
File file = new File(path);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
	fis = new FileInputStream(path);
    fos = new FileOutputStream(destinationPath, true);
    int input = 0;
    while((input = fis.read()) != -1) {
    fos.write(input);
    System.out.print(input + ", ");
    }
    fos.write('\n');  
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} finally {
	try {
    	if(fos != null) fos.close();
        if(fis != null) fis.close();
    } catch (IOException e) {}
}
  1. new File 파일을 생성하는게 아니라 파일을 다루는 객체를 생성
  2. 닫을때는 outputStream 먼저 닫아줌

0개의 댓글