在java中如何追加文本到存在的文件中?
在java中如何追加文本到存在的文件中?
回答:
Java 7+
如果你只需要执行一次,则使用Files类很容易:
try { Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
注意:NoSuchFileException如果文件不存在,上述方法将抛出。它还不会自动追加换行符(追加到文本文件时通常会需要此换行符)。
但是,如果你要多次写入同一文件,则上述操作必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,使用缓冲写入器更好:
try(FileWriter fw = new FileWriter("myfile.txt", true); BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
笔记:
FileWriter
构造函数的第二个参数将告诉它追加到文件中,而不是写入新文件。(如果文件不存在,将创建它。)BufferedWriter
对于昂贵的作家(例如FileWriter
),建议使用。- 使用a
PrintWriter
可访问println
你可能习惯使用的语法System.out
。 - 但是
BufferedWriter
和PrintWriter
包装器不是严格必需的。
较旧的Java
try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
异常处理
如果你需要对旧版Java进行健壮的异常处理,它将变得非常冗长:
FileWriter fw = null;BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
以上是 在java中如何追加文本到存在的文件中? 的全部内容, 来源链接: utcz.com/qa/424676.html