本篇主要使用Java實現文件名的批量修改。做數據挖掘實驗,當數據集量不充足時,通常使用交叉法進行多次實驗,提取不重複的訓練集、驗證集和測試集,這時能夠批量隨機修改文件名能夠大大提高開發效率。
package app;
import java.io.*;
public class Test {
public static void main(String[] args) {
String path = "D:\\ORL1\\s";
//文件類型
String suffix = ".bmp";
for (int i = 1; i <= 40; i++) {
String pathTemp = path + i + "\\";
for (int j = 10; j >= 1; j--) {
rename(pathTemp + j + suffix, "" + (j + 1), suffix);
}
rename(pathTemp + "11" + suffix, "1", suffix);
}
}
public static boolean rename(String AbsolutePath, String newName,
String Suffix) {
File file = new File(AbsolutePath);
if (!file.exists()) {
System.out.println(AbsolutePath + " doesn't exist!");
return false;
}
String filename = file.getAbsolutePath();
if (filename.indexOf(".") >= 0) {
filename = filename.substring(0, filename.lastIndexOf("\\") + 1);
filename += newName;
}
if (!file.renameTo(new File(filename + Suffix))) {
System.out.println(AbsolutePath + " fails to rename!");
return false;
}
return true;
}
}