java 对文件内容进行替换工作

读取文件代码如下:


   
   
  1. File file = new File( "C:/Users/Administrator/Desktop/test1.json");
  2. try {
  3. String content = FileUtils.readFileToString(file, "utf-8");
  4. System.out.println(content);
  5. } catch (Exception e) {
  6. e.printStackTrace();
  7. }

这是应该算是代码最少的去读办法了。

缺点:要导入commons-io-2.4.jar 文件


替换文本内的内容:


   
   
  1. /**
  2. * 替换文本文件中的 非法字符串
  3. * @param path
  4. * @throws IOException
  5. */
  6. public void replacTextContent(String path) throws IOException{
  7. //原有的内容
  8. String srcStr = "name:";
  9. //要替换的内容
  10. String replaceStr = "userName:";
  11. // 读
  12. File file = new File(path);
  13. FileReader in = new FileReader(file);
  14. BufferedReader bufIn = new BufferedReader(in);
  15. // 内存流, 作为临时流
  16. CharArrayWriter tempStream = new CharArrayWriter();
  17. // 替换
  18. String line = null;
  19. while ( (line = bufIn.readLine()) != null) {
  20. // 替换每行中, 符合条件的字符串
  21. line = line.replaceAll(srcStr, replaceStr);
  22. // 将该行写入内存
  23. tempStream.write(line);
  24. // 添加换行符
  25. tempStream.append(System.getProperty( "line.separator"));
  26. }
  27. // 关闭 输入流
  28. bufIn.close();
  29. // 将内存中的流 写入 文件
  30. FileWriter out = new FileWriter(file);
  31. tempStream.writeTo(out);
  32. out.close();
  33. System.out.println( "====path:"+path);
  34. }






转https://blog.csdn.net/qq_27292113/article/details/79425723
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值