자바에서 파일을 읽고 쓰는 방법은 무엇인가요?
자바(Java)에서 파일을 읽고 쓰는 방법에는 여러 가지가 있으며, 주로 `java.io` 패키지와 `java.nio` 패키지를 사용합니다.
여기서는 기본적인 파일 읽기 및 쓰기 방법을 예제와 함께 설명하겠습니다.
--- 1. 파일 읽기 1-1. `FileReader`와 `BufferedReader` 사용하기 (텍스트 파일 읽기) ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReadExample { public static void main(String[] args) { String filePath = "example.txt"; try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } ``` - `FileReader`는 문자 단위로 파일을 읽습니다.
- `BufferedReader`는 버퍼를 사용하여 라인 단위로 읽을 때 효율적입니다.
- `try-with-resources` 문을 사용하여 자원을 자동으로 해제합니다.
1-2. `Files` 클래스 사용하기 (Java 7 이후) ```java import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; import java.util.List; public class FileReadExampleNIO { public static void main(String[] args) { String filePath = "example.txt"; try { List
- 간단한 텍스트 파일 읽기에 적합합니다.
--- 2. 파일 쓰기 2-1. `FileWriter`와 `BufferedWriter` 사용하기 (텍스트 파일 쓰기) ```java import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriteExample { public static void main(String[] args) { String filePath = "output.txt"; try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) { bw.write("안녕하세요, 자바 파일 쓰기 예제입니다.
"); bw.newLine(); // 개행 bw.write("두 번째 줄입니다.
"); } catch (IOException e) { e.printStackTrace(); } } } ``` - `FileWriter`는 문자 단위로 파일을 씁니다.
- `BufferedWriter`와 함께 사용하면 효율적으로 쓸 수 있습니다.
2-2. `Files` 클래스 사용하기 (Java 7 이후) ```java import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; import java.util.Arrays; import java.util.List; public class FileWriteExampleNIO { public static void main(String[] args) { String filePath = "output.txt"; List
- 매우 간단하게 파일 쓰기를 처리할 수 있습니다.
--- 3. 바이너리 파일 읽고 쓰기 파일 읽기 ```java import java.io.FileInputStream; import java.io.IOException; public class FileBinaryReadExample { public static void main(String[] args) { String filePath = "image.jpg"; try (FileInputStream fis = new FileInputStream(filePath)) { byte[] buffer = new byte[1024]; int bytesRead; while((bytesRead = fis.read(buffer)) != -1) { // buffer에 bytesRead 만큼의 데이터가 읽힘 // 예: 다른 스트림으로 쓰거나 처리 가능 } } catch(IOException e) { e.printStackTrace(); } } } ``` 파일 쓰기 ```java import java.io.FileOutputStream; import java.io.IOException; public class FileBinaryWriteExample { public static void main(String[] args) { String filePath = "output.jpg"; byte[] data = {/* 바이너리 데이터 */}; try (FileOutputStream fos = new FileOutputStream(filePath)) { fos.write(data); } catch(IOException e) { e.printStackTrace(); } } } ``` - `FileInputStream`과 `FileOutputStream`은 바이트 단위로 파일을 읽고 씁니다.
- 이미지, 영상, 오디오 등 바이너리 파일 처리에 사용합니다.
--- 정리 | 작업 | 클래스 및 메서드 | 특징 | | ------------- | -------------------------------------- | ---------------------------- | | 텍스트 읽기 | `FileReader` + `BufferedReader` | 라인 단위 읽기, 간단 사용 | | | `Files.readAllLines(Path)` | 파일 전체 읽기, 편리 | | 텍스트 쓰기 | `FileWriter` + `BufferedWriter` | 문자 단위 쓰기 | | | `Files.write(Path, List
궁금하신 점 있으면 언제든 문의해주세요!