입력 스트림 (Input Stream)
출력 스트림 (Output Stream)
// 바이트 스트림 예시
FileInputStream fis = new FileInputStream("test.dat");
FileOutputStream fos = new FileOutputStream("output.dat");
// 문자 스트림 예시
FileReader reader = new FileReader("text.txt");
FileWriter writer = new FileWriter("output.txt");
// 주 스트림 예시
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
// 보조 스트림 예시
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"));
public class BufferedStreamExample {
public void readWithBuffer() {
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("input.txt"))) {
int data;
while ((data = bis.read()) != -1) {
// 버퍼를 통한 효율적인 읽기
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// 파일 처리 로직
} catch (IOException e) {
// 예외 처리
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 파일 처리 로직
} catch (IOException e) {
// 예외 처리
}
public void copyFile(String source, String target) {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target)) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void processTextFile(String filename) {
try (BufferedReader reader = new BufferedReader(
new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
// 텍스트 처리 로직
}
} catch (IOException e) {
e.printStackTrace();
}
}
컴퓨터의 입출력 장치(디스크, 네트워크, 키보드 등)와 프로그램 간에는 속도 차이가 큽니다. 프로그램이 처리 속도가 빠른 반면, 입출력 장치의 속도는 상대적으로 느리기 때문에, 작은 데이터를 여러 번 주고받을 경우 성능 저하가 발생할 수 있습니다.
버퍼를 사용하면 데이터를 한 번에 모아서 처리하여 입출력 작업의 빈도를 줄이고, 전체적인 성능을 개선할 수 있습니다. 이는 자바의 파일 IO 작업에서 특히 중요합니다.