前置代码:
SimpleDateFormat yMFormat=new SimpleDateFormat("yyyyMM");
Date thisTime = new Date();
String yM = yMFormat.format(thisTime);
//System.out.println("当前年月为"+yM);
String path = "C:\\Users\\Administrator\\Desktop\\test";
String pathHandled = path+"\\已处理\\"+yM;
File handled = new File(pathHandled);
if(!handled.exists()){
boolean b1 = handled.mkdirs();
}
File dir = new File(path);
File[] files = dir.listFiles(); //获取当前目录下文件以及文件夹对象
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() && files[i].exists()){
String fileName=files[i].getName();
File checkfile=new File(pathHandled+"\\"+fileName);
//操作代码
}
1.移动文件到文件夹
等待移动的文件名:checkfile
要移动的文件名:files[i]
第一种:
files[i].renameTo(checkfile);
返回值为布尔类型,可以用boolean check = files[i].renameTo(checkfile);来判断是否移动成功。
第二种:
FileUtils.moveFile(files[i],checkfile);
建议用第二种,第一种不会返回相应的错误信息。
2.重命名同名文件为 “-”+数字
要求:待移动的文件中没有“-”符号
if(checkfile.exists() && checkfile.isFile()){
int indexdot = fileName.lastIndexOf(".");
int maxnum=1;
File[] handledFiles=handled.listFiles();
for(int j=0;j<handledFiles.length;j++)
{
String checkName=handledFiles[j].getName();
int indexbar = checkName.lastIndexOf("-");
if(indexbar!=-1){
if(fileName.substring(0,indexdot).equals(checkName.substring(0, indexbar))){
String str=checkName.substring(indexbar+1,checkName.lastIndexOf("."));
if(str!="" && str!=null){
int num=Integer.parseInt(str)+1;
if(maxnum<num) {maxnum=num;}
}
}
}
}
System.out.println("重复文件的最大编号为"+maxnum);
checkfile=new File(pathHandled+"\\"+fileName.substring(0,indexdot)+"-"+maxnum+fileName.substring(indexdot,fileName.length()));
System.out.println("移动文件为"+checkfile);
}