写入文件而不覆盖或附加而不、文件

2023-09-08 08:45:05 作者:猪哼哼

我正在用 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).txtoverflow(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.