본문 바로가기
프로그래밍 언어/JAVA

JAVA - 파일 입출력 ( FileOutputStream, FileInputStream, FileReader, FileWriter)

by DGDD(Developer) 2023. 6. 20.

JAVA에서 파일 입출력은 파일을 읽고 쓰는것을 말합니다. JAVA에서 파일을 읽고 쓸 때 주로 사용되는 클래스로는 (FileOutputStream/FileInputStream), (FileReader, FileWriter) 가 있습니다.  2가지 다 파일을 읽고 쓰는것은 맞지만 파라미터로 받을 수 있는 데이터에 있어서 차이가 존재 합니다.

1. FileReader, FileWriter

  •  FileReader는 파일에서 문자를 읽는 데 사용되는 클래스로 파일에서 문자들을 문자별로 읽기 때문에 텍스트 파일을 읽는 데 적합합니다.  
try (FileReader reader = new FileReader("file.txt")) {
    int character;
    while ((character = reader.read()) != -1) {
        // Process the character
    }
} catch (IOException e) {
    // Handle exception
}
  • FileWriter는 파일에서 문자를 쓰는 데 사용되는 클래스로 Reader와 동일하게 문자 지향 클래스입니다. 파일을 쓸 때 파일이 존재하지 않으면 새 파일을 생성하고 이미 파일이 존재한다면 기존 파일을 덮어쓰기해서 파일에 문자를 씁니다.
try (FileWriter writer = new FileWriter("file.txt")) {
    writer.write("Hello, World!");
} catch (IOException e) {
    // Handle exception
}

2.FileInputStream, FileOutputStream

  • FileInputStream은 파일에 바이트를 읽는 데 사용되는 바이트 지향 클래스로 파일을 바이트 단위로 읽어 모든 종류의 파일을 읽는데 적합합니다. 
try (FileInputStream inputStream = new FileInputStream("file.txt")) {
    int byteValue;
    while ((byteValue = inputStream.read()) != -1) {
        // Process the byte
    }
} catch (IOException e) {
    // Handle exception
}
  • FileOutputStreamdms 바이트 파일을 쓰는 데 사용되는 클래스로 Writer랑 동일하게 파일이 존재하지 않는 경우 새로 생성하고 존재 한다면 기존 파일에 덮어씁니다.
try (FileOutputStream outputStream = new FileOutputStream("file.txt")) {
    byte[] data = "Hello, World!".getBytes();
    outputStream.write(data);
} catch (IOException e) {
    // Handle exception
}

파일 입출력에서 주로 사용하는 클래스와 기본적인 사용법에 대해서 알아봤습니다. 파일 입출력을 할 때 파일을 읽고 쓰는 과정에서 언제든지 장애가 발생할 수 있기 때문에 try/catch 문을 사용해서 예외 처리를 하는 것이 중요합니다.