Как писать в файл на 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
, одну строку, просто и красиво.
Listlist = Arrays.asList("Line 1", "Line 2"); Files.write(Paths.get("app.log"), list);
ПрочитатьFiles.write examples
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
Для режима добавления передайтеtrue
в качестве второго аргумента вFileWriter
// 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