So schreiben Sie in eine Datei in Java - BufferedWriter
In Java können wirBufferedWriter
verwenden, um Inhalte in eine Datei zu schreiben.
// 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
Wenn möglich, wird stattdessenFiles.write
verwendet, eine Zeile, einfach und nett.
Listlist = Arrays.asList("Line 1", "Line 2"); Files.write(Paths.get("app.log"), list);
Lesen SieFiles.write examples
1. BufferedWriter
Schreiben Sie Inhalte in eine Datei.
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); } } }
Ausgabe
app.log
This is the content to write into file
Übergeben Sie im Append-Modustrue
als zweites Argument inFileWriter
// 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 (Old School Style)
Vor dem JDK 7try-resources
müssen wir dieclose()
manuell behandeln. Eine schmerzhafte Erinnerung, mal sehen:
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); } } } }
Ausgabe
app.log
This is the content to write into file