您这样做是为了记录目的吗?如果有的话有为此有几个库。其中最受欢迎的两个是Log4j and Logback.
Java 7+
对于一次性任务,文件类让这变得容易:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful:上述方法会抛出一个NoSuchFileException
如果该文件尚不存在。它也不会自动附加换行符(在附加到文本文件时您通常需要这样做)。另一种方法是同时通过CREATE
and APPEND
选项,如果文件尚不存在,它将首先创建该文件:
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
是比较快的:
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
}
Notes:
- 第二个参数为
FileWriter
构造函数将告诉它追加到文件,而不是写入新文件。 (如果该文件不存在,则会创建该文件。)
- Using a
BufferedWriter
推荐给昂贵的作家(例如FileWriter
).
- Using a
PrintWriter
让您可以访问println
您可能习惯的语法System.out
.
- But the
BufferedWriter
and PrintWriter
包装器并不是绝对必要的。
旧爪哇
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
}
}