Java How to append text to a file
By:Roy.LiuLast updated:2019-08-11
In Java, we can use Files.write and StandardOpenOption.APPEND to append text to a file.
try { // Create file if doesn't exist, write to it // If file exist, append it Files.write(Paths.get("app.log"), "Hello World".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException x) { //...
1. Files.write
Append a List into an existing file.
FileExample.java
package com.mkyong; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class FileExample { public static void main(String[] args) { Charset utf8 = StandardCharsets.UTF_8; List<String> list = Arrays.asList("Line 1", "Line 2"); try { Files.write(Paths.get("app.log"), list, utf8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException x) { System.err.format("IOException: %s%n", x);
Output
Run 1st time.
app.log
Line 1 Line 2
Run 2nd time.
app.log
Line 1 Line 2 Line 1 Line 2
2. BufferedWriter
2.1 To enable append mode, pass a true as second argument to FileWriter.
BufferedWriterExample.java
package com.mkyong; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; public class BufferedWriterExample { public static void main(String[] args) { List<String> list = Arrays.asList("Line 1", "Line 2"); // append mode try (FileWriter writer = new FileWriter("app.log", true); BufferedWriter bw = new BufferedWriter(writer)) { for (String s : list) { bw.write(s); bw.write("\n"); } catch (IOException e) { System.err.format("IOException: %s%n", e);
2.2 Before JDK 7, we need to close everything manually.
ClassicBufferedWriterExample.java
package com.mkyong; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class ClassicBufferedWriterExample { public static void main(String[] args) { BufferedWriter bw = null; FileWriter fw = null; try { String content = "Hellow"; fw = new FileWriter("app.log", true); 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);
From:一号门
COMMENTS