将索引添加到现有文件的文件名(file.txt => file_1.txt) [英] Add index to filename for existing file (file.txt => file_1.txt)
问题描述
像我有一个文件 myfile.txt
同时 myfile.txt
存在于目标文件夹中 - 我需要复制我的文件,名称为 myfile_1.txt
同时如果我有一个文件 myfile.txt
,但是destintation文件夹包含 myfile.txt
和 myfile_1.txt
- 生成的文件名必须是 myfile_2.txt
因此,功能与Microsoft操作系统中的文件夹创建非常相似。
最好的方法是什么?
未验证代码:
文件f = new File(filename);
String extension =;
int g = 0;
while(f.exists()){
int i = f.lastIndexOf('。');
if(i> 0)
{extension = fileName.substring(i + 1); }
f.renameTo(f.getPath()+\+(f.getName()+ g)+。+ extension)
}
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?
Untested Code:
File f = new File(filename);
String extension = "";
int g = 0;
while(f.exists()) {
int i = f.lastIndexOf('.');
if (i > 0)
{ extension = fileName.substring(i+1); }
f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension)
}
这篇关于将索引添加到现有文件的文件名(file.txt => file_1.txt)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!