将索引添加到现有文件的文件名中(file.txt =& gt file_1.txt) [英] Add index to filename for existing file (file.txt => file_1.txt)
问题描述
如果文件已经存在,我想在文件名中添加索引,这样我就不会覆盖它.
I want to add an index to a filename if the file already exists, so that I don't overwrite it.
就像我有文件 myfile.txt
一样,并且目标文件夹中同时存在 myfile.txt
-我需要复制名称为 myfile_1的文件.txt
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
同时如果我有一个文件 myfile.txt
,但目标文件夹包含 myfile.txt
和 myfile_1.txt
-生成的文件名必须为 myfile_2.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
因此,该功能与在Microsoft操作系统中创建文件夹非常相似.
So the functionality is very similar to the creation of folders in Microsoft operating systems.
做到这一点的最佳方法是什么?
What's the best approach to do that?
推荐答案
未经测试的代码:
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++;
}
这篇关于将索引添加到现有文件的文件名中(file.txt =& gt file_1.txt)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!