在Java中,我们可以使用Files.write
和StandardOpenOption.APPEND
将文本追加到文件中。
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
将List
追加到现有文件中。
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 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);
}
}
}
输出量
第一次运行。
app.log
Line 1
Line 2
运行第二次。
app.log
Line 1
Line 2
Line 1
Line 2
2. BufferedWriter
2.1要启用append
模式, append
true
作为第二个参数传递给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 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在JDK 7之前,我们需要手动关闭所有内容。
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);
}
}
}
}
参考文献
- Files.write Java文档
- BufferedWriter JavaDocs
- FileWriter JavaDocs
- StandardOpenOption JavaDocs
- Java –如何创建和写入文件
标签: 附加文件 io Java nio
翻译自: https://mkyong.com/java/java-how-to-append-text-to-a-file/