java ファイルにデータを書き込む

javaで、ファイルにデータを書き込む手順を記述してます。
環境
- OS windows11 home
- java 17.0.2
手順
ファイルにデータを書き込むには、「PrintWriter」を使用します。
PrintWriter writer = new PrintWriter(ファイル名, 文字コード);
writer.println("書き込む内容");
writer.close();
実際に使用してみます。
import java.io.*;
public class App {
public static void main(String[] args) throws Exception {
try {
PrintWriter writer = new PrintWriter("C:/java/test/src/sample.txt", "UTF-8");
writer.println("hello");
writer.println("world");
writer.close();
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
「sample.txt」に書き込みされていることが確認できます。
※ファイルが存在しない場合はファイルが作成され、すでに書き込みされているデータは上書きされます。

追記
追記して書き込む場合は「FileWriter」を使用します。
import java.io.*;
public class App {
public static void main(String[] args) throws Exception {
try {
FileWriter file = new FileWriter("C:/java/test/src/sample.txt", true);
PrintWriter writer = new PrintWriter(file);
writer.println("hello");
writer.println("world");
writer.close();
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
実行結果

-
前の記事
Error: Cannot find module ‘X’ の解決方法 2025.06.18
-
次の記事
kotlin 変数にnullを代入する 2025.06.19
コメントを書く