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 문을 사용해서 예외 처리를 하는 것이 중요합니다.
'프로그래밍 언어 > JAVA' 카테고리의 다른 글
JAVA - 배열 복사하기 (2) | 2024.03.15 |
---|---|
Java - 문자열(String) 과 정수(int) 변환 (0) | 2024.03.13 |
Java - 대소문자 구분 / 대소문자 변환 (문자) (0) | 2024.03.13 |
JAVA - == 와 .equals() 차이 (0) | 2023.06.19 |
FileOutputStream을 활용한 안전한 파일 저장 방법 (0) | 2023.06.19 |