Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create files with similar names using Java without overwriting existing file

Tags:

java

I was wondering if it is possible to create multiple files with similar names, without overwriting the current file.

for example: if I have a file: xyz.txt next time when i create it should be : xyz(1).txt

try {
  File makefile = new File("output.txt");
  FileWriter fwrite = new FileWriter(makefile);
  fwrite.write("example file");
  fwrite.flush();
  fwrite.close();
} catch (IOException e) {
  e.printStackTrace();
}

so if I re-run this program my current file should not be overwritten. I have already tried and if condition with a flag variable to add number as prefix to the file name.

I want to know if there are any Java commands to avoid overwriting an existing file.

like image 698
Daniel Euchar Avatar asked Apr 24 '12 09:04

Daniel Euchar


People also ask

How do I stop Java overwriting?

The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior.

How can I write without overwriting file?

Please use only the 'Append Range' activity, it will append the data next to the data that already exists in excel. For eg: If your excel have data till A61, append range will write the data from A62. Thanks.

Does FileWriter overwrite existing file?

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.

Does new file overwrite Java?

In this case, a new file is created when we instantiate the FileOutputStream object. If a file with a given name already exists, it will be overwritten.


Video Answer


2 Answers

Not in java as already indicated by @Greg Kopff. But you can work around something like this:

  int count = 0;

  public void createFile(String name) throws IOException
  {
    File f;
    f = new File(name);
    if (!f.exists())
    {
      f.createNewFile();
    }
    else
    {
      count++;
      createFile(name + (count));
    }
  }
like image 140
Bitmap Avatar answered Sep 30 '22 12:09

Bitmap


i want to know if there are any native java commands to stop overwriting [and append a numeral to the filename]

Not in the core Java libraries, no.

like image 21
Greg Kopff Avatar answered Sep 30 '22 12:09

Greg Kopff