把某书的部分章节拍成照片传给朋友,需要把文件名改成页码,遂写了代码实现
public class Test {
public static void main(String[] args) throws Exception{
changeIMGFileName("d:\\backup\\140591\\桌面\\待上传照片\\六爻洗髓", 117);
}
/**
* 照片批量改名,需要传入文件夹路径
*/
public static void changeIMGFileName(String path, int startPage) {
File directory = new File(path);
if (!directory.exists()) {
System.out.println("指定目录" + path + "不存在!");
return;
} else if (!directory.isDirectory()) {
System.out.println( path + "不是一个目录!");
return;
}
File[] images = getFileList(path, ".jpg");
// 先获取文件名数组并排序
List<String> fileNameList = getSortedFileName(images);
// 重命名
for (int i = 0; i < images.length; i++) {
if (images[i].getName().toLowerCase().endsWith(".jpg")){
File newNameFile = new File(path, (fileNameList.indexOf(images[i].getName()) + startPage) +".jpg");
if (!images[i].renameTo(newNameFile)) {
System.out.println("文件名错误!程序中止");
System.out.println("此时操作的文件为:" + images[i].getName());
return;
}
}
}
System.out.println("Done!!");
}
/**
* 获取指定目录下指定后缀名的文件
*/
private static File[] getFileList(String path, String suffix) {
suffix = suffix.toLowerCase();
if (!suffix.startsWith(".")) {
suffix = "." + suffix;
}
final String suffixFinal = suffix;
File directory = new File(path);
File[] files = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.getName().toLowerCase().endsWith(suffixFinal)) return true;
return false;
}
});
return files;
}
/**
* 获取文件名数组并排序
* 对文件名的解析仅用于特定情况,须根据问题变化
* 文件名示例:IMG_20150316_172845.jpg
*/
private static List<String> getSortedFileName(File[] images) {
List<String> fileNameList = new ArrayList<String>();
for (int i = 0; i < images.length; i++) {
String fileName = images[i].getName();
if (fileName.toLowerCase().endsWith(".jpg")){
fileNameList.add(fileName);
}
}
Comparator comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int time1 = Integer.parseInt(getTimeStr(o1));
int time2 = Integer.parseInt(getTimeStr(o2));
if (time1 < time2) return -1;
if (time1 > time2) return 1;
return 0;
}
};
Collections.sort(fileNameList, comparator);
return fileNameList;
}
/**
* 获取指定字符串中的某部分
* 字符串示例:IMG_20150316_172845.jpg
*/
private static String getTimeStr(String fileName) {
int start = fileName.lastIndexOf("_") + 1;
int end = fileName.indexOf(".");
return fileName.substring(start, end);
}
}