Java如何将文件下的所有文件进行批量更改和替换
- 将F盘下tmp文件夹下的文件循环取出
- 进行文件的替换(这里将李替换成1)
- 修改完成写入到文件夹中
public class Test {
public static void main(String[] args) throws IOException {
List fileStr = Files.walk(Paths.get("F:\\tmp"))
.filter(Files::isRegularFile)
.collect(Collectors.toList());
String target = "李";
String replacement = "1";
fileStr.forEach(x->modify( x.toString(), target, replacement));
}
public static void modify(String path, String target, String replacement) {
File file = new File(path);
if (file.exists()) {
modifyFileContent(file, target, replacement);
} else {
System.out.println("文件不存在"+ path);
}
}
/**
* 修改文件中的内容
* @param file 文件
* @param target 被替换的字符串
* @param replacement 替换字符串
*/
public static void modifyFileContent(File file, String target, String replacement) {
System.out.println("开始修改文件:+file.getName(), 替换 "+target+"为"+replacement);
StringBuilder sb = new StringBuilder();
//修改的行数
int cnt = 0;
//替换所在的行
int rowLine = 0;
//换行符
String enter = System.getProperty("line.separator");
PrintWriter pw = null;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
for (line = br.readLine(); line != null; line = br.readLine()) {
rowLine++;
if (line.contains(target)) {
line = line.replace(target, replacement);
System.out.println("替换所在行:"+rowLine);
cnt++;
}
//数据暂存在 StringBuilder 中
if (rowLine == 1) {
sb.append(line);
} else {
sb.append(enter).append(line);
}
}
pw = new PrintWriter(new FileWriter(file));
pw.print(sb);
} catch (FileNotFoundException e) {
System.out.println("文件不存在!"+ e);
System.exit(1);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
}