为现有文件的文件名添加索引(file.txt => file_1.txt)

如果文件已经存在,我想为文件名添加一个索引,这样我就不会覆盖它。

就像我有一个文件myfile.txt并且同时myfile.txt存在于目标文件夹中 – 我需要复制我的文件名为myfile_1.txt

同时如果我有一个文件myfile.txt ,但destintation文件夹包含myfile.txtmyfile_1.txt – 生成的文件名必须是myfile_2.txt

因此,该function与在Microsoft操作系统中创建文件夹非常相似。

这样做的最佳方法是什么?

未经测试的代码:

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

使用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 } 

这将检查是否存在例如file.txt并将返回file-1.txt

您也可以从使用apache commons-io库中受益。 它在FileUtils和FilenameUtils类中有一些有用的文件操作方法。

尝试此链接部分回答您的查询。

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(); 

一旦获得了正确的文件集,请附加适当的后缀以创建新文件。