将索引添加到现有文件的文件名(file.txt => file_1.txt) [英] Add index to filename for existing file (file.txt => file_1.txt)

查看:142
本文介绍了将索引添加到现有文件的文件名(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆