业务需求: 由于最近公司需要上传一批文件且要求文件名要有功能描述并且有文件的创建时间 这批文件博主之前就是按功能命名的 但是五六十个文件手动改名就太浪费时间了 SO 写了这么个小工具类
功能: 获取到某一目录下的全部文件 然后获取文件名 并通过DOS 命令获取当前文件的创建时间 然后截取到年月日后 使用分隔符与原名拼接 这样 写代码十分钟 跑起来两分钟 轻松搞定
import java.io.*;
/**
* @author:manbu
* @data 2020/1/16- 17:07
* @TODO: 批量修改文件名 -- ,目前支持Windows 使用DOS命令获取文件创建时间 注意输入输出的目录不能是一个目录 否则会造成文件被删除无法恢复 且没有重命名的文件
* @console:
*/
public class FileTest {
public static void main(String[] args) {
/**默认产出文件名格式 文件名-2020_1_16.后缀*/
/**文件原名与创建时间分隔符*/
String te1 = "-";
/**文件创建时间 年月日分隔符*/
String te2 = "_";
/**文件存放目录*/
String inputFilePath = "C:\\Users\\manbu\\Desktop\\test\\";
/**改名后文件存放目录*/
String outputFilepath = "C:\\Users\\manbu\\Desktop\\new\\";
File file = new File(inputFilePath);// 文件目录
try {
for (File demoFile : file.listFiles()) {
try {
/** 获取文件名字 TODO 注意 文件全名不能包含超过两个.(点)*/
String name = demoFile.getName();
/** 当前File 是目录 demoFile.isDirectory() 当前File 是文件 demoFile.isFile() */
if (demoFile.isFile()) {
/*使用DOS命令*/
String last = demoFile.getName().substring(name.lastIndexOf("."), name.length());
if (last.equals(".chls")) {
Process ls_proc = Runtime.getRuntime().exec(
"cmd.exe /c dir " + file.getAbsolutePath() + " /tc");// 通过DOS获得的创建时间
InputStream is = ls_proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str;
int i = 0;
while ((str = br.readLine()) != null) {
i++;
if (i == 6) {
System.out.println("Create time:" + str.substring(0, 10)); //创建时间获取
String star = demoFile.getName().substring(0, name.lastIndexOf(".")) + te1 + ((str.substring(0, 10)).replace("/", te2));
File newFile = new File(outputFilepath + star + last);
demoFile.renameTo(newFile); //改名
}
}
}
}
} catch (IOException e) {
System.out.println(demoFile.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}