跳到主要内容

Java 批量重命名文件:正则匹配、冲突检测与安全处理

· 阅读需 1 分钟
Apache王也道长
软件开发者与技术作者

文件重命名工具

你是否还在为文件批量重命名发愁,下面的代码很好的解决了文件重命名问题

批量重命名最重要的不是执行速度,而是避免覆盖和不可逆错误。可靠工具应先生成变更预览,检测重名、非法字符和跨文件系统问题,再让用户确认执行。

实现代码

String[] args = new String[]{"C:\\tests"};
String matchRegex = "(\\d{6})";
String replaceRegex = "$1.json";

Pattern pattern = Pattern.compile(matchRegex);

File file = new File(args[0]);
if (file.exists()) {
File[] files = file.listFiles();
if (files != null) {
System.out.println("files : " + files.length);
for (File f : files) {
Matcher matcher = pattern.matcher(f.getName());
if (matcher.matches()) {
String s = matcher.replaceAll(replaceRegex);
System.out.println(s);
f.renameTo(new File(f.getParent() + File.separator + s));
}
}
}
}

本文阅读量:--

总访问量 -- · 访客数 --