Java中怎么把文本追加到已经存在的文件
我需要重复把文本追加到现有文件中。我应该怎么办?
回答一
你是想实现日志的目的吗?如果是的话,这里有几个库可供选择,最热门的两个就是Log4j 和 Logback了
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。它也不会自动追加到新一行(像你追加文件的时候经常干的那样)。另一个方法就是传入 CREATE和 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 codeout.println("more text");//more code
} catch (IOException e) {//exception handling left as an exercise for the reader
}
Notes:
FileWriter 构造器的第二个参数就是决定是否追加文件,而不是重新写一个文件(如果文件不存在,那会被新建一个)。使用 BufferedWriter 是更为推荐的,比起代价昂贵的writer (例如 FileWriter)。用PrintWriter使得你可以使用 println 语法(可能经常在System.out中使用的)
但是BufferedWriter和PrintWriter包装器不是必须的
Older 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}
}
文章翻译自Stack Overflow:https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java