Java之修改文件内容:字符串逐行替换

依赖包:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

源码:

 1 package auto.script.interfaceupdate.base;
 2 
 3 import org.apache.commons.io.FileUtils;
 4 
 5 import java.io.File;
 6 import java.io.IOException;
 7 import java.util.List;
 8 
 9 /**
10  * @Auther:gongxingrui
11  * @Date:2018-05-10
12  * @Description: 修改文件内容:字符串逐行替换
13  **/
14 public class MyFileUtils {
15     /**
16      * 修改文件内容:字符串逐行替换
17      *
18      * @param file:待处理的文件
19      * @param oldstr:需要替换的旧字符串
20      * @param newStr:用于替换的新字符串
21      */
22     public static boolean modifyFileContent(File file, String oldstr, String newStr) {
23         List<String> list = null;
24         try {
25             list = FileUtils.readLines(file, "UTF-8");
26             for (int i = 0; i < list.size(); i++) {
27                 String temp = list.get(i).replaceAll(oldstr, newStr);
28                 list.remove(i);
29                 list.add(i, temp);
30             }
31             FileUtils.writeLines(file, "UTF-8", list, false);
32         } catch (IOException e) {
33             e.printStackTrace();
34         }
35 
36         return true;
37     }
38 
39     public static boolean modifyFileContent(String filePath, String oldstr, String newStr) {
40         return modifyFileContent(new File(filePath), oldstr, newStr);
41     }
42 
43 }

 

posted @ 2018-05-10 18:21  星瑞  阅读(4533)  评论(0编辑  收藏  举报