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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391046.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391046.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391046.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python機器學習預測_使用Python和機器學習預測未來的股市趨勢

python機器學習預測Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works withou…

線程系列3--Java線程同步通信技術

上一篇文章我們講解了線程間的互斥技術,使用關鍵字synchronize來實現線程間的互斥技術。根據不同的業務情況,我們可以選擇某一種互斥的方法來實現線程間的互斥調用。例如:自定義對象實現互斥(synchronize("自定義對象")…

Python數據結構之四——set(集合)

Python版本:3.6.2 操作系統:Windows 作者:SmallWZQ 經過幾天的回顧和學習,我終于把Python 3.x中的基礎知識介紹好啦。下面將要繼續什么呢?讓我想想先~~~嗯,還是先整理一下近期有關Python基礎知識的隨筆吧…

volatile關鍵字有什么用

問題:volatile關鍵字有什么用 在工作的時候,我碰到了volatile關鍵字。但是我不是非常了解它。我發現了這個解釋 這篇文章已經解釋了問題中的關鍵字的細節了,你們曾經用過它嗎或者見過正確使用這個關鍵字的樣例 回答 Java中同步的實現大多是…

knn 機器學習_機器學習:通過預測意大利葡萄酒的品種來觀察KNN的工作方式

knn 機器學習Introduction介紹 For this article, I’d like to introduce you to KNN with a practical example.對于本文,我想通過一個實際的例子向您介紹KNN。 I will consider one of my project that you can find in my GitHub profile. For this project, …

MMU內存管理單元(看書筆記)

http://note.youdao.com/noteshare?id8e12abd45bba955f73874450e5d62b5b&subD09C7B51049D4F88959668B60B1263B5 筆記放在了有道云上面了,不想再寫一遍了。 韋東山《嵌入式linux完全開發手冊》看書筆記轉載于:https://www.cnblogs.com/coversky/p/7709381.html

Java中如何讀取文件夾下的所有文件

問題:Java中如何讀取文件夾下的所有文件 Java里面是如何讀取一個文件夾下的所有文件的? 回答一 public void listFilesForFolder(final File folder) {for (final File fileEntry : folder.listFiles()) {if (fileEntry.isDirectory()) {listFilesFor…

github pages_如何使用GitHub Actions和Pages發布GitHub事件數據

github pagesTeams who work on GitHub rely on event data to collaborate. The data recorded as issues, pull requests, and comments become vital to understanding the project.在GitHub上工作的團隊依靠事件數據進行協作。 記錄為問題,請求和注釋的數據對于…

c# .Net 緩存 使用System.Runtime.Caching 做緩存 平滑過期,絕對過期

1 public class CacheHeloer2 {3 4 /// <summary>5 /// 默認緩存6 /// </summary>7 private static CacheHeloer Default { get { return new CacheHeloer(); } }8 9 /// <summary>10 /// 緩存初始化11 /// </summary>12 …

python 實現分步累加_Python網頁爬取分步指南

python 實現分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作為數據科學家&#xff0c;我們一直在尋找…

Java 到底有沒有析構函數呢?

Java 到底有沒有析構函數呢&#xff1f; ? ? Java 到底有沒有析構函數呢&#xff1f;我沒能找到任何有關找個的文檔。如果沒有的話&#xff0c;我要怎么樣才能達到一樣的效果&#xff1f; ? ? ? 為了使得我的問題更加具體&#xff0c;我寫了一個應用程序去處理數據并且說…

關于雙黑洞和引力波,LIGO科學家回答了這7個你可能會關心的問題

引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 關于雙黑洞和引力波&#xff0c;LIGO科學家回答了這7個你可能會關心的問題 最近&#xff0c;引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 大家興奮之余&am…

如何使用HTML,CSS和JavaScript構建技巧計算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小費計算器是根據總賬單的百分比計算小費的計算器。 Lets build one now.讓我們現在建立一個。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于MLOps的MLflow簡介第1部分:Anaconda環境

在這三部分的博客中跟隨了演示之后&#xff0c;您將能夠&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的數…

[WCF] - 使用 [DataMember] 標記的數據契約需要聲明 Set 方法

WCF 數據結構中返回的只讀屬性 TotalCount 也需要聲明 Set 方法。 [DataContract]public class BookShelfDataModel{ public BookShelfDataModel() { BookList new List<BookDataModel>(); } [DataMember] public List<BookDataModel>…

sql注入語句示例大全_SQL Group By語句用示例語法解釋

sql注入語句示例大全GROUP BY gives us a way to combine rows and aggregate data.GROUP BY為我們提供了一種合并行和匯總數據的方法。 The data used is from the campaign contributions data we’ve been using in some of these guides.使用的數據來自我們在其中一些指南…

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么?

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么&#xff1f; 我有一個會被多個線程同時修改的Map 在Java的API里面&#xff0c;有3種不同的實現了同步的Map實現 HashtableCollections.synchronizedMap(Map)ConcurrentHashMap 據我所知&#xff0c;HashT…

pymc3 貝葉斯線性回歸_使用PyMC3估計的貝葉斯推理能力

pymc3 貝葉斯線性回歸內部AI (Inside AI) If you’ve steered clear of Bayesian regression because of its complexity, this article shows how to apply simple MCMC Bayesian Inference to linear data with outliers in Python, using linear regression and Gaussian ra…

Hadoop Streaming詳解

一&#xff1a; Hadoop Streaming詳解 1、Streaming的作用 Hadoop Streaming框架&#xff0c;最大的好處是&#xff0c;讓任何語言編寫的map, reduce程序能夠在hadoop集群上運行&#xff1b;map/reduce程序只要遵循從標準輸入stdin讀&#xff0c;寫出到標準輸出stdout即可 其次…

mongodb分布式集群搭建手記

一、架構簡介 目標 單機搭建mongodb分布式集群(副本集 分片集群)&#xff0c;演示mongodb分布式集群的安裝部署、簡單操作。 說明 在同一個vm啟動由兩個分片組成的分布式集群&#xff0c;每個分片都是一個PSS(Primary-Secondary-Secondary)模式的數據副本集&#xff1b; Confi…