日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java中怎么把文本追加到已经存在的文件

發布時間:2023/11/29 java 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java中怎么把文本追加到已经存在的文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Java中怎么把文本追加到已经存在的文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。