如何将文本附加到 Java 中的现有文件? [英] How to append text to an existing file in Java?
问题描述
我需要将文本重复附加到 Java 中的现有文件.我该怎么做?
I need to append text repeatedly to an existing file in Java. How do I do that?
推荐答案
您这样做是为了记录日志吗?如果是这样,有几个用于此的库.两个最受欢迎的是 Log4j 和 登录.
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
对于一次性任务,文件类让这一切变得简单:
For a one-time task, the Files class makes this easy:
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
.它也不会自动附加换行符(在附加到文本文件时您经常需要它).另一种方法是同时传递 CREATE
和 APPEND
选项,如果文件不存在,它们将首先创建文件:
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
但是,如果你要多次写入同一个文件,上面的代码片段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作.在这种情况下,BufferedWriter
更快:
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
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
). - 使用
PrintWriter
可以让您访问println
语法,您可能已经习惯了System.out
的语法. - 但是
BufferedWriter
和PrintWriter
包装器并不是绝对必要的.
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
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 进行强大的异常处理,它会变得非常冗长:
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
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 中的现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!