说明:
1.renameTo(dest)
renameTo是不保留移动,并且如果参数的目的文件已经存在,则不移动了,而且什么都不做,返回值为false
javadoc 中对这个的描述是 it might not succeed if a file with the destination abstract pathname already exists.
2.getAbsolutePath() 是没有最后斜线 / 的路径
代码如下,最好先拿文件做实验,以免不熟悉丢文件
import java.io.File;
public class CommonTool {
public static void moveFile(String oldPath,String newPath) {
File oldDir = new File(oldPath);
File newDir = new File(newPath);
if(!oldDir.exists()) return;
if(!newDir.exists()) newDir.mkdirs();
for(File f : oldDir.listFiles()) {
if(f.isFile()
&& (f.getName().endsWith("rmvb") || f.getName().endsWith("mp4"))) {
f.renameTo(new File(newDir.getAbsolutePath() + "/" + f.getName()));//renameTo 是不保留移动,getAbsolutePath() 是没有最后斜线 / 的路径
} else if(f.isDirectory()) {
moveFile(f.getAbsolutePath(),newPath);
}
}
}
public static void changeName(String path) {
File dir = new File(path);
if(!dir.isDirectory()) return;
int changeNum = 0;
for(File f : dir.listFiles()) {
f.renameTo(new File(dir.getAbsolutePath() + "/" + changeNum +".rmvb"));
//changeNum++;
}
}
public static void main(String[] args) {
//CommonTool.moveFile("D:/main","D:/movie");//把D盘main 的以及子文件夹的所有视频不保留移动到D盘movie 下面
CommonTool.changeName("D:/movie");//把文件夹下的全都变成1.rmvb,2.rmvb
}
}