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.
这篇关于写入文件而不覆盖或附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:写入文件而不覆盖或附加


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01