对于一般批量文件重命名处理:
// 第一种
public static void main(String[] args) throws IOException {
File[] files = new File("/xxxxx/xxx").listFiles();
int num = 1;
for (File file : files) {
// System.out.println("修改前文件名称是:"+file.getName());
String rootPath = file.getParent();
// System.out.println("根路径是:"+rootPath);
File newFile = new File(rootPath + File.separator + num+"newname");
// System.out.println("修改后文件名称是:"+newFile.getName());
if (file.renameTo(newFile)) {
System.out.println("修改成功!");
num++;
} else {
System.out.println("修改失败!");
}
}
}
但是上述方法在文件名乱码的情况下就失效了,所以需要下面的方法:
在linux底下,文件都有一个对应的索引的,可以通过ls -i >> inums.txt,命令先将索引号输出到一个inums.txt文件,然后拿到文件的索引号,再通过索引号来更改文件名。
//第二种
public static void main(String[] args) throws IOException {
File file = new File("/xxx/inums.txt");
ArrayList<String> inums = new ArrayList<String>();
int num = 1;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
inums.add(lineTxt.split(" ")[0]);
}
bufferedReader.close();
for (String inum : inums) {
cmd(inum,num);
num++;
}
}
public static void cmd(String inum, int num) {
try {
String cmd = "find /oldpath -inum " + inum + " -exec mv {} /newpath" + num + "newname \\;";
String[] cmds = new String[] { "sh", "-c", cmd };
System.out.println(cmd);
//注意:不能直接使用Process ps = Runtime.getRuntime().exec(cmd);
Process ps = Runtime.getRuntime().exec(cmds);
ps.waitFor();
} catch (Exception e) {
System.out.println(e);
}
}