Add index to filename for existing file (file.

2019-02-27 08:14发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2019-02-27 08:55

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

查看更多
\"骚年 ilove
3楼-- · 2019-02-27 08:58

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.

查看更多
我命由我不由天
4楼-- · 2019-02-27 09:03

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

查看更多
欢心
5楼-- · 2019-02-27 09:04

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++;    
}
查看更多
登录 后发表回答