如果文件已经存在,我想为文件名添加索引,这样我就不会覆盖它。
就像我有一个文件myfile.txt
并且同时myfile.txt
存在于目标文件夹中一样 - 我需要复制带有名称的文件myfile_1.txt
同时,如果我有一个文件myfile.txt
,但目标文件夹包含myfile.txt
并且myfile_1.txt
生成的文件名必须是myfile_2.txt
因此该功能非常类似于在 Microsoft 操作系统中创建文件夹。
最好的方法是什么?
如果文件已经存在,我想为文件名添加索引,这样我就不会覆盖它。
就像我有一个文件myfile.txt
并且同时myfile.txt
存在于目标文件夹中一样 - 我需要复制带有名称的文件myfile_1.txt
同时,如果我有一个文件myfile.txt
,但目标文件夹包含myfile.txt
并且myfile_1.txt
生成的文件名必须是myfile_2.txt
因此该功能非常类似于在 Microsoft 操作系统中创建文件夹。
最好的方法是什么?
使用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();
获得正确的文件集后,请附加适当的后缀以创建新文件。
未经测试的代码:
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++;
}