问题
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.
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?
回答1:
Check if the file exists, if so rename it. Using File.exists
and FileUtils.moveFile
You would need to do this recursively until no conflict is found.
回答2:
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.
回答3:
"A new file with the same name" doesn't make sense in most file systems.
In your example, you've got three files with different names:
- overflow(1).txt
- overflow(2).txt
- overflow(3).txt
The bit in brackets is still part of the name. If you want to emulate that behaviour, you'll have to:
- Detect the presence of the "plain" filename (if you want to write to that if it doesn't exist)
- Start counting at 1, and work out the "new" filename each time by removing the extension, adding the count in brackets, then putting the extension back
- Keep counting until you find a filename which doesn't exist
回答4:
String dirPath = "./";
String fileName = dirPath + "overflow.txt";
if(new File(dirPath + fileName).exist())
{
int counter = 0;
while(new File(dirPath + "overflow(" + ++counter + ").txt").exist());
fileName = "overflow(" + counter + ").txt";
}
回答5:
When you instanciate the File object, verify if it exists, if it does, just rename it by adding the braces and number, and check again.
来源:https://stackoverflow.com/questions/11055695/writing-to-a-file-without-overwriting-or-appending