最新我想从网上下载漫画图片,但下载后的文件名是网站自定义的,看不出来先后顺序,只好手动排序改文件名。我去网上搜了一下发现有很多种改名的方式,不过都跟我想要的效果不太一样,就把这些综合了一下写出了下文。
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class newstring {
static List<File> list; //存放排序后的文件
static String newString = "";//新字符串
static int index=1; //当前文件名的前缀
public static void main(String[] args) {
String path = "";//文件所在路径,所有文件的根目录
list = getFileSort(path);
recursiveTraversalFolder();
}
/**
* 获取目录下所有文件(按时间排序)
*
* @param path
* @return
*/
public static List<File> getFileSort(String path) {
List<File> list = getFiles(path, new ArrayList<File>());
if (list != null && list.size() > 0) {
Collections.sort(list, new Comparator<File>() {
public int compare(File file, File newFile) {
if (file.lastModified() < newFile.lastModified()) {
return -1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return 1;
}
}
});
}
return list;
}
/**
*
* 获取目录下所有文件
*
* @param realpath
* @param files
* @return
*/
public static List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles();
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
/**
* 批量修改文件名
*/
public static void recursiveTraversalFolder() {
if (null == list || list.size() == 0) {
System.out.println("文件夹是空的!");
return;
} else {
File newDir = null;// 文件所在文件夹路径+新文件名
String newName = "";// 新文件名
String fileName = null;// 旧文件名
File parentPath = new File("");// 文件所在父级路径
for (File file : list) {
fileName = file.getName();
System.out.println("fileName:"+fileName);
parentPath = file.getParentFile();
if (index < 10) {
newString = "00" + index + ".jpg";
} else if (index < 100) {
newString = "0" + index + ".jpg";
} else {
newString = "" + index + ".jpg";
}
newName = fileName.replaceAll(fileName, newString);// 新名字
newDir = new File(parentPath + "/" + newName);// 文件所在文件夹路径+新文件名
file.renameTo(newDir);// 重命名
System.out.println("修改后:" + newDir);
index++;
}
}
}