Paul
Paul

Reputation: 97

Writing to a file without overwriting or appending

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?

Upvotes: 0

Views: 1507

Answers (5)

Eng.Fouad
Eng.Fouad

Reputation: 117597

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";
}

Upvotes: 1

kaliatech
kaliatech

Reputation: 17867

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.

Upvotes: 3

Ed Morales
Ed Morales

Reputation: 1037

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.

Upvotes: 0

John B
John B

Reputation: 32949

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500525

"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

Upvotes: 2

Related Questions