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