java读取文件并重新创建新文件

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();
			}
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值