Create files with similar names using Java without overwriting existing file

后端 未结 4 789
忘了有多久
忘了有多久 2021-01-03 05:43

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 tim

相关标签:
4条回答
  • 2021-01-03 05:58

    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));
        }
      }
    
    0 讨论(0)
  • 2021-01-03 06:13

    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.

    0 讨论(0)
  • 2021-01-03 06:18

    Take a look at the method File.createTempFile()

    To create the new file, the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. If the prefix is too long then it will be truncated, but its first three characters will always be preserved. If the suffix is too long then it too will be truncated, but if it begins with a period character ('.') then the period and the first three characters following it will always be preserved. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix.

    0 讨论(0)
  • 2021-01-03 06:22

    While similar to Bitmap's response, I came up with this java code (which seems to work). I don't know if it's the most efficient, but...

    For my example, I am assuming the file will be a .txt file

    String fileName = "output.txt"; 
    File aFile = new File(fileName);
    
    int fileNo = 0;
    while(aFile.exists() && !aFile.isDirectory()) { 
        fileNo++; 
        String newName = fileName.replaceAll(".txt", "(" + fileNo + ").txt");   
        aFile = new File(newName);
    } 
    
    0 讨论(0)
提交回复
热议问题