写入文件,而不会覆盖或附加 [英] Writing to a file without overwriting or appending
问题描述
我用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屋!