tools- 重命名
作者:生
- 2023-11-11 上海
本文字数:1806 字
阅读完需:约 6 分钟
///////////////////////////////////////
递归给定路径下的所有文件进行重命名。
///////////////////////////////////////
Java
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* 递归给定路径下的所有文件
*/
public class RecursionPathRename {
private Map<String, String> renameMap;
private String path;
public static void main(String[] args) {
// 文件路径
String path = "F:\\Download";
Map renameMap = new HashMap<String, String>();
// key:替换前的内容 value:替换后的内容
renameMap.put("()", "");
renameMap.put("()", "");
new RecursionPathRename().setPath(path).setRenameMap(renameMap).startRename();
}
private void startRename() {
if (CollectionUtils.isEmpty(getRenameMap()) || StringUtils.isEmpty(getPath())) {
System.out.println("renameMap or path is empty.");
return;
}
rename(getPath());
}
private void rename(String path) {
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File childFile : files) {
if (childFile.isDirectory()) {
rename(childFile.getPath());
} else {
doRename(childFile);
}
}
} else {
doRename(file);
}
}
private void doRename(File file) {
String fileName = file.getName();
getRenameMap().forEach((oldValue, newValue) -> {
if (fileName.contains(oldValue)) {
String tag = file.getPath().replace(oldValue, newValue);
System.out.println("tag:" + tag);
File dest = new File(tag);
file.renameTo(dest);
}
});
}
public Map<String, String> getRenameMap() {
return renameMap;
}
public RecursionPathRename setRenameMap(Map<String, String> renameMap) {
this.renameMap = renameMap;
return this;
}
public String getPath() {
return path;
}
public RecursionPathRename setPath(String path) {
this.path = path;
return this;
}
}
复制代码
Rust
use std::fs;
use std::path::Path;
fn main() {
let path = Path::new(r#".\"#);
let rename_str = RenameStr::new(String::from("xxx"), String::from(""));
recursive_directory(path, &rename_str);
}
fn recursive_directory(path: &Path, rename_str: &RenameStr) {
for entry in fs::read_dir(path).expect("读取目录失败,目录或许不存在!") {
if let Ok(entry) = entry {
let file = entry.path();
let filename = file.to_str().unwrap();
if file.is_dir() {
recursive_directory(Path::new(&filename), rename_str)
}
if filename.contains(rename_str.before()) {
let new_filename = filename.replace(rename_str.before(), rename_str.after());
match fs::rename(filename, &new_filename) {
Ok(_) => println!("{} => {}", filename, new_filename),
Err(e) => panic!("{} => {} error : {}", filename, new_filename, e)
}
}
}
}
}
struct RenameStr {
before: String,
after: String,
}
impl RenameStr {
pub fn new(before: String, after: String) -> Self {
Self { before, after }
}
pub fn before(&self) -> &str {
&self.before
}
pub fn after(&self) -> &str {
&self.after
}
}
复制代码
划线
评论
复制
发布于: 2023-11-11阅读数: 21
生
关注
还未添加个人签名 2019-08-17 加入
还未添加个人简介
评论