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

不想你离开。 提交于 2020-01-30 07:41:50

问题


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.txt exists in destination folder - I need to copy my file with name myfile_1.txt

And same time if I have a file myfile.txt, but destintation folder contains myfile.txt and myfile_1.txt - generated filename has to be myfile_2.txt

So the functionality is very similar to the creation of folders in Microsoft operating systems.

What's the best approach to do that?


回答1:


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



回答2:


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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/14254664/add-index-to-filename-for-existing-file-file-txt-file-1-txt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!