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

时间:2022-02-01 11:19:44
 import org.junit.Test;

 import java.io.*;

 /**
* User: HYY
* Date: 13-8-18
* Time: 下午8:11
* To change this template use File | Settings | File Templates.
*/
public class ReplaceStr {
private File fileRootDir = new File("D:\\ahgw\\src\\com\\ahgw");//根目录文件
private String saveDirPath = "D:\\ahgw\\src\\com\\ahgw2";//替换之后的新的一个目录名称
private String srcStr = "baoxiu";//要替换的原字符串
private String destStr = "ahgw";//目的字符串 @Test
public void test() throws IOException { if (!fileRootDir.exists()) {
throw new ExceptionInInitializerError("根目录不存在");
} File saveRootDir = new File(saveDirPath);
if (!saveRootDir.exists()) {
saveRootDir.mkdirs();
} File[] files = fileRootDir.listFiles();
operate(files);
} public void operate(File[] files) throws IOException {
for (File file : files) {
if (file.isDirectory()) {
if (file.listFiles().length == 0) {
file.mkdir();
System.out.println(file.listFiles().length);
} else {
operate(file.listFiles());
}
} else {
System.out.println("srcPath=" + file.getPath());
System.out.println("fileRootDir.getPath()=" + fileRootDir.getPath()); String savePath = saveDirPath + file.getPath().substring(fileRootDir.getPath().length());
// String savePath = fileRootDir.getParent() + File.separator + saveDirName + File.separator + file.getName();
File saveFile = new File(savePath);
System.out.println("savePath=" + savePath);
replace(file, saveFile);
}
}
} /**
* 根据源文件,修改相应的字符串,并保存起来
*
* @param file 源文件
* @param saveFile 保存的目标文件
*/
public void replace(File file, File saveFile) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
PrintWriter pw = new PrintWriter(saveFile);
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll(srcStr, destStr);
pw.println(line);
}
br.close();
pw.close();
} public static void main(String[] args) throws IOException { }
}