Write
Coddyの「Javaでのファイル操作」コースのレッスン 5/11。
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コンストラクタの第2引数としてtrueを指定していることに注目してください。
チャレンジ
簡単以前の "coddy.txt" という名前のファイルが与えられています。このファイルに次のテキストを追記してください:
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) {
// ここにコードを記述してください
}
}