Add index to filename for existing file (file.txt => file_1.txt)

后端 未结 4 777
孤城傲影
孤城傲影 2021-01-23 05:18

I want to add an index to a filename if the file already exists, so that I don\'t overwrite it.

Like if I have a file myfile.txt and same time myfile.

相关标签:
4条回答
  • 2021-01-23 05:48

    Try this link partly answers your query.

    https://stackoverflow.com/a/805504/1961652

        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setIncludes(new String[]{"**/myfile*.txt"});
        scanner.setBasedir("C:/Temp");
        scanner.setCaseSensitive(false);
        scanner.scan();
        String[] files = scanner.getIncludedFiles();
    

    once you have got the correct set of files, append a proper suffix to create a new file.

    0 讨论(0)
  • 2021-01-23 05:50

    Untested Code:

    File f = new File(filename);
    String extension = "";
    int g = 0;
    int i = f.lastIndexOf('.');
    extension = fileName.substring(i+1);
    
    while(f.exists()) {      
      if (i > 0) 
      {  f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension); }
      else
      {  f.renameTo(f.getPath() + "\" + (f.getName() + g)); }     
    
      g++;    
    }
    
    0 讨论(0)
  • 2021-01-23 05:52

    Using commons-io:

    private static File getUniqueFilename( File file )
    {
        String baseName = FilenameUtils.getBaseName( file.getName() );
        String extension = FilenameUtils.getExtension( file.getName() );
        int counter = 1
        while(file.exists())
        {
            file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
        }
        return file
    }
    

    This will check if for instance file.txt exist and will return file-1.txt

    0 讨论(0)
  • 2021-01-23 06:14

    You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.

    0 讨论(0)
提交回复
热议问题