写入文件,而不会覆盖或附加 [英] Writing to a file without overwriting or appending

查看:294
本文介绍了写入文件,而不会覆盖或附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java编写一个程序,输出写入到一个.txt文件。每次我运行该文件被覆盖的程序。我不想使用append开关和数据添加到文件

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 是文件名,而我运行程序三次,文件溢出(1).TXT 溢出(2).TXT 溢出(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.

如何才能实现这一目标?

How can this be achieved?

推荐答案

检查文件是否存在第一。如果是这样,修改名称。

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.

这篇关于写入文件,而不会覆盖或附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆