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.mzph.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…