Write
Coddy의 Java 파일 처리 코스 레슨 — 11개 중 5번째.
Java에서 파일에 쓰려면 FileWriter 클래스를 사용할 수 있습니다:
try {
FileWriter writer = new FileWriter("data.txt");
writer.write("This the new contect of data.txt file!");
writer.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}위의 코드는 "data.txt" 파일에 일부 텍스트를 작성합니다. IOException 예외를 처리해야 함에 유의하세요.
기본적으로 텍스트는 기존의 모든 텍스트를 덮어씁니다. 기존 파일 내용에 텍스트를 추가하려면 다음을 사용하세요:
FileWriter writer = new FileWriter("data.txt", true);FileWriter 생성자의 두 번째 인수로 true가 사용된 점에 유의하세요.
챌린지
쉬움이전의 "coddy.txt"라는 이름의 파일이 주어집니다. 이 파일에 다음 텍스트를 추가(Append)하세요:
This is the end of the file, but only the beginning...마지막으로, 새로운 파일 내용을 출력하세요.
직접 해보기
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) {
// 여기에 코드를 작성하세요
}
}