JAVA
FileInputStream과 FileOutputStream
jiyoon12
2025. 5. 28. 23:39
1. FileInputStream은 바이트 단위로 파일에서 데이터를 읽어오는 기반 스트림입니다. 텍스트 파일뿐만 아니라 이미지, 비디오, 실행 파일 등 바이너리 데이터에도 사용됩니다.
- 루트 폴더에서 a.txt 파일을 생성하고 텍스트를 넣어 주세요
Hello World.
by tenco.
- 실습하기
package ch02;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class MyFileInputStream {
public static void main(String[] args) {
// 파일을 바이트 단위로 읽어 들이는 녀석
FileInputStream in = null;
int readData;
try {
in = new FileInputStream("a.txt");
readData = in.read();
System.out.println("readData: " + readData);
System.out.println("readData: " + (char)readData);
readData = in.read();
System.out.println("readData: " + readData);
System.out.println("readData: " + (char)readData);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package ch02;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 파일 입력 스트림을 사용해 보자.
*/
public class MyFileInputStream2 {
public static void main(String[] args) {
// a.txt 파일에서 바이트 단위로 데이터를 읽어서 콘솔창에 출력해 보자.
// 주의: 한글은 3바이트 기반이라 1바이트씩 읽으면 깨짐 발생할 수 있음.
try (FileInputStream in = new FileInputStream("a.txt")) {
// 사전 기반 지식 ->
// 파일에서 바이트 단위로 데이터를 읽을 때 더이상 읽을 데이터가 없다면
// 정수값 -1을 반환 한다.
int readData;
while ((readData = in.read()) != -1) {
System.out.print((char)readData);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
2. FileOutputStream은 바이트 단위로 데이터를 파일에 직접 쓰는 기반 스트림입니다. 텍스트 파일뿐만 아니라 이미지, 비디오, 실행 파일 등 바이너리 데이터에도 사용됩니다.
package ch02;
import java.io.FileOutputStream;
/**
* 파일 출력 스트림을 사용해 보자
*/
public class MyFileOutputSystem {
public static void main(String[] args) {
String data = "Hello, Java FileOutputSystem abc abc 안녕 반가워";
// new FileOutputStream("output.txt") <-- 파일 없으면 새로 생성해서 데이터를 쓴다.
// Append 모드 활성화 처리(두번째 인자값)
// new FileOutputStream("output.txt",true) <-- 파일 없으면 새로 생성해서 데이터를 쓴다.
try (FileOutputStream fos = new FileOutputStream("output.txt", true)) {
// 문자열 data 값을 byte 배열로 변환 시켜 보자.
byte[] dataBytes = data.getBytes();
// [72, 101, 108 .. .. ..]
// 바이트 단위로 파일에 데이터를 쓴다.
fos.write(dataBytes);
System.out.println("파일 출력 완료: output.txt");
// 참고: output.txt 파일을 열었을 때 텍스트로 보이는 이유는
// 에디터가 바이트 데이터를 문자로 해석해서 보여줬기 떄문이다.
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3. my1.txt 생성 후 데이터를 읽어 my2.txt 로 데이터 내보내기
package my_test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MyFileStream {
public static void main(String[] args) {
String data = "Hello, Java FileOutputSystem abc abc 안녕 반가워";
try (FileInputStream in = new FileInputStream("my1.txt");
FileOutputStream fos = new FileOutputStream("my2.txt")) {
int readData;
while ((readData = in.read()) != -1) {
System.out.print((char) readData);
fos.write(readData);
}
byte[] dataBytes = data.getBytes();
fos.write(dataBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}