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

随声附和 提交于 2019-12-02 00:14:17

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

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

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

muffy

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.

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