Writing to a file without overwriting or appending(写入文件而不覆盖或附加)
问题描述
我正在用 Java 编写一个程序,其中的输出被写入一个 .txt 文件.每次我运行程序时,文件都会被覆盖.我不想使用追加开关并将数据添加到文件中.
I am writing a program in Java where the output is written to a .txt file. Each time I run the program the file is overwritten. I do not want to use the append switch and add data to the file.
我想要它,所以每次运行程序时都会创建一个同名的新文件.比如overflow.txt
是文件名,我运行程序3次,文件overflow(1).txt
,overflow(2).txt
,overflow(3).txt
应该做.
I would like to have it so a new file, with the same name, is created each time I run the program. For example, if overflow.txt
is the file name, and I run the program three times, the files overflow(1).txt
, overflow(2).txt
, and overflow(3).txt
should be made.
如何做到这一点?
推荐答案
先检查文件是否存在.如果是,请修改名称.
Check if the file exists first. If so, modify the name.
String origName = "overflow";
String ext = ".txt";
int num = 1;
file = new File(origName + ext);
while (file.exists()) {
num++;
file = new File(myOrigFileName +"(" + num + ")" + ext);
}
根据实际需要修改.问题不是很清楚.
Modify depending on actual requirements. Question is not very clear.
这篇关于写入文件而不覆盖或附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:写入文件而不覆盖或附加


- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01