Java将整个文件夹里的文本中的字符串替换成另外一个字符串(可用于项目复制,变成另一个项目)

 1 import org.junit.Test;
 2 
 3 import java.io.*;
 4 
 5 /**
 6  * User: HYY
 7  * Date: 13-8-18
 8  * Time: 下午8:11
 9  * To change this template use File | Settings | File Templates.
10  */
11 public class ReplaceStr {
12     private File fileRootDir = new File("D:\ahgw\src\com\ahgw");//根目录文件
13     private String saveDirPath = "D:\ahgw\src\com\ahgw2";//替换之后的新的一个目录名称
14     private String srcStr = "baoxiu";//要替换的原字符串
15     private String destStr = "ahgw";//目的字符串
16 
17     @Test
18     public void test() throws IOException {
19 
20         if (!fileRootDir.exists()) {
21             throw new ExceptionInInitializerError("根目录不存在");
22         }
23 
24         File saveRootDir = new File(saveDirPath);
25         if (!saveRootDir.exists()) {
26             saveRootDir.mkdirs();
27         }
28 
29         File[] files = fileRootDir.listFiles();
30         operate(files);
31     }
32 
33     public void operate(File[] files) throws IOException {
34         for (File file : files) {
35             if (file.isDirectory()) {
36                 if (file.listFiles().length == 0) {
37                     file.mkdir();
38                     System.out.println(file.listFiles().length);
39                 } else {
40                     operate(file.listFiles());
41                 }
42             } else {
43                 System.out.println("srcPath=" + file.getPath());
44                 System.out.println("fileRootDir.getPath()=" + fileRootDir.getPath());
45 
46                 String savePath = saveDirPath + file.getPath().substring(fileRootDir.getPath().length());
47 //                String savePath = fileRootDir.getParent() + File.separator + saveDirName + File.separator + file.getName();
48                 File saveFile = new File(savePath);
49                 System.out.println("savePath=" + savePath);
50                 replace(file, saveFile);
51             }
52         }
53     }
54 
55     /**
56      * 根据源文件,修改相应的字符串,并保存起来
57      *
58      * @param file     源文件
59      * @param saveFile 保存的目标文件
60      */
61     public void replace(File file, File saveFile) throws IOException {
62         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
63         if (!saveFile.getParentFile().exists()) {
64             saveFile.getParentFile().mkdirs();
65         }
66         PrintWriter pw = new PrintWriter(saveFile);
67         String line;
68         while ((line = br.readLine()) != null) {
69             line = line.replaceAll(srcStr, destStr);
70             pw.println(line);
71         }
72         br.close();
73         pw.close();
74     }
75 
76     public static void main(String[] args) throws IOException {
77 
78     }
79 }
原文地址:https://www.cnblogs.com/wuyou/p/3279910.html