[ 학습 목표 ]
- 텍스트 파일을 읽고 쓰는 방법을 이해한다.
- File, FileWriter, BufferedReader 등의 클래스를 활용한다.
- 도서 정보 또는 사용자 정보를 파일에 젖아하고 불러올 수 있다.
[ 이론 ]
1. 파일 입출력 기본 개념
1) 파일 쓰기 (FileWriter)
- FileWriter를 사용해 해당 파일이 작성한 경로에 없으면 파일이 생성되고 안에 내용이 입력된다.
- 파일이 있으면 해당 파일에 입력이 된다.
import java.io.FileWriter;
import java.io.IOException;
public class WriterExample {
public static void main(String[] args) {
try {
// 저장할 경로와 파일명
FileWriter writer = new FileWriter("./studyjavachatgpt/day18/output.txt");
writer.write("Hello, Java!\n");
writer.write("파일 입출력 연습 중입니다.");
writer.close(); // 꼭 닫아줘야 데이터가 저장됨
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) 파일 읽기 (BufferedReader)
- 해당 경로에 파일이 있고 null값이 아니면 파일 안의 내용을 출력함.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("./studyjavachatgpt/day18/output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 실무에서 자주 사용하는 구조
1) BufferedWriter + FileWriter
BufferedWriter bw = new BufferedWriter(new FileWriter("파일경로", true)); // true는 append
bw.write("문자열");
bw.newLine(); // 줄 바꿈
bw.close();
3. 추가 팁
- 디렉토리 구조를 유지할 경우, 경로를 지정할 때는 상대 경로로 한다.
BufferedWriter bw = new BufferedWriter(new FileWriter("src/data/booklist.txt", true));
[ 실습 ]
✅ 실습 예제 1: 사용자 입력을 파일에 저장
import java.io.*;
import java.util.Scanner;
public class SaveToFile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("저장할 내용을 입력하세요: ");
String input = sc.nextLine();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("memo.txt", true));
bw.write(input);
bw.newLine();
bw.close();
System.out.println("저장 완료!");
} catch (IOException e) {
System.out.println("파일 저장 실패: " + e.getMessage());
}
}
}
✅ 예제 2: 파일에서 한 줄씩 읽어오기
import java.io.*;
public class LoadFromFile {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("memo.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println("읽은 내용: " + line);
}
br.close();
} catch (IOException e) {
System.out.println("파일 읽기 실패: " + e.getMessage());
}
}
}
[ 과제 ]
✅ 과제 1: 도서 정보를 파일로 저장
1권당 한 줄씩 "제목,저자,출판연도" 형식으로 저장
예: 클린 코드,로버트 C. 마틴,2008
public class Book {
private String title;
private String author;
private String year;
public Book(String title, String author, String year) {
this.title = title;
this.author = author;
this.year = year;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getYear() {
return year;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setYear(String year) {
this.year = year;
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class SaveBook {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("./studyjavachatgpt/day18/ex1/books.txt", true));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("제목, 저자, 출판연도 입력해주세요.");
System.out.print("제목: ");
String bookTitle = br.readLine();
System.out.print("저자: ");
String bookAuthor = br.readLine();
System.out.print("출판연도: ");
String bookYear = br.readLine();
bw.write(bookTitle + ", " + bookAuthor + ", " + bookYear);
bw.newLine(); // 줄바꿈
br.close();
bw.close();
System.out.println("파일 저장 성공");
} catch (IOException e) {
System.out.println("파일저장 실패: " + e.getMessage());
}
}
}
✅ 과제 2: 저장된 파일을 읽고 도서 목록 출력
저장된 파일을 한 줄씩 읽고 Book 객체 생성
리스트에 저장한 뒤 출력
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadBook {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("./studyjavachatgpt/day18/ex1/books.txt"));
//Book 객체로 리스트에 저장.
List<Book> bookList = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(", ");
if (parts.length == 3) {
Book book = new Book(parts[0], parts[1], parts[2]);
bookList.add(book);
}
}
for (Book book : bookList) {
System.out.println("제목: " + book.getTitle() + ", 저자: " + book.getAuthor() + ", 출판연도: " + book.getYear());
}
br.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[ 메모 ]
- 처음으로 사용해본 기능이었다. FileWriter 클래스를 사용해서 텍스트 파일을 생성하고 그 파일에 내용을 저장하고, 또 불러와서 출력하는 기능이 신기했다.
- 이 기능을 사용해서 전에 만들어본 도서 등록 시스템에도 적용할 수 있지 않을까 싶다.