在java中 ,使用renameTo方法剪切文件的时候,若目标文件中有重名的文件,程序会执行失败。为了解决这个问题,写出如下代码,实现文件自动编号。
用到如下方法:
1 . renameTo(File dest) 返回值类型为boolean
Renames the file denoted by this abstract pathname.
2 . listFiles(FilenameFilter filter) 返回值类型为File[ ]
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
3 . getAbsolutePath() 返回值类型为String
Returns the absolute pathname string of this abstract pathname. 具体代码如下:
package File;
import java.io.File;
import java.io.FilenameFilter;
public class CopyRenameDemo {
/*
* 在挪动文件的时候如果遇见同问文件,
* 保留同名文件
* 将要挪过来的文件进行编号
*/
public static void main(String[] args) {
//新建文件,为即将要移动的文件
File file =new File("D:\\a.txt");
//新建文件,为移动的目标目录
File file2=new File("D:\\1");
//执行copy,获取目标目录;里面重名或者相同结构的文件的个数
copy(file,file2);
System.out.println(copy(file,file2));
//判断文件个数是否为0
if(copy(file,file2)==0){
//若文件个数为0,代表目标目录里面没有重名或者符合命名规则的文件,文件不需要重新命名
file.renameTo(new File(file2.getAbsolutePath()+"\\"+"a.txt"));
}
else
//若文件个数不为0,代表目标目录里面有重名或符合命名规则的文件,则按照命名规则将文件重新命名
file.renameTo(new File(file2.getAbsolutePath()+"\\"+"a-"+copy(file,file2)+".txt"));
}
private static int copy(File file, File file2) {
//筛选文件名字符合规格的文件,将其放入数组
File[]fs=file2.listFiles(new FilenameFilter() {
@Override
//规定筛选规则
public boolean accept(File dir, String name) {
return name.matches("a.txt|a-\\d.txt");
}
});
//返回值为数组的长度,为重名或者符合命名规则的文件个数
return fs.length;
}
}