1.实现代码
public class TestUtil2 {
public static void main(String[] args) throws Exception {
String path = "C:\\Users\\Administrator\\Desktop\\test";
File file = new File(path);
File[] tempList = file.listFiles();
System.out.println("该目录下对象个数:" + tempList.length);
for (int i = 0; i < tempList.length; i++) {// 循环读取文件夹下面的所有文件
if (tempList[i].isFile()) {
String a = tempList[i].getPath();
System.out.println("文 件:" + tempList[i]);
// 将符合条件的字符串srcStr 替换成 replaceStr
String srcStr = "456";
String replaceStr = "张三";
// 读
File file1 = new File(a);
FileReader in = new FileReader(file1);
BufferedReader bufIn = new BufferedReader(in);
// 替换
String line = null;
List<String> list = new ArrayList<>();
while ((line = bufIn.readLine()) != null) {// 按行读取文件夹里面的内容
if (line.indexOf("此处填写你需要寻找的关键字") != -1) {// 如果与你相等的关键字一样可以进行相应的操作
// 例如:替换成你想要的文字
line = line.replaceAll(srcStr, replaceStr);
} else {
// todo写自己想要的操作
}
}
FileOutputStream os = new FileOutputStream(path);
PrintWriter pw = new PrintWriter(os);
for (String o : list) {
pw.println(o);// 此处输出的就是你想要的文件内容
// pw.print(o); //此处就是不换行进行操作
}
// 关闭 输入流
bufIn.close();
in.close();
pw.close();
os.close();
}
}
}
}