Javaでファイルに書き込む方法– BufferedWriter
Javaでは、BufferedWriter
を使用してコンテンツをファイルに書き込むことができます。
// jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); }
Note
可能であれば、代わりにFiles.write
を使用します。1行で、シンプルでわかりやすいです。
Listlist = Arrays.asList("Line 1", "Line 2"); Files.write(Paths.get("app.log"), list);
1. BufferedWriter
コンテンツをファイルに書き込みます。
FileExample1.java
package com.example; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileExample1 { public static void main(String[] args) { String content = "This is the content to write into file\n"; // If the file doesn't exists, create and write to it // If the file exists, truncate (remove all content) and write to it try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } } }
出力
app.log
This is the content to write into file
追加モードの場合、FileWriter
の2番目の引数としてtrue
を渡します
// If the file exists, append to it try (FileWriter writer = new FileWriter("app.log", true); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); }
2. BufferedWriter(旧式スタイル)
JDK 7try-resources
の前に、close()
を手動で処理する必要があります。 痛い記憶、これを見てみましょう:
FileExample2.java
package com.example; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileExample2 { public static void main(String[] args) { BufferedWriter bw = null; FileWriter fw = null; try { String content = "This is the content to write into file\n"; fw = new FileWriter("app.log"); bw = new BufferedWriter(fw); bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { System.err.format("IOException: %s%n", ex); } } } }
出力
app.log
This is the content to write into file