import java.io.*;
public class MDFileReadingAndWriting { private static String path = "../demo/src/main/resources/md/"; private static String suffix = ".md"; public static void main(String[] args) { //源文件名称 String fileName = path + "群聊管理" + suffix; //新文件名称 String pathname = path + "群聊管理new" + suffix; //原字符集 String[] regex = {"**接口地址**:`", "**produces**:`[\"*/*\"]`", "**consumes**:`[\"application/json\"]`","(int64)", "(int32)"}; //新字符集 String[] replacment = {"**请求地址**:`https://www.", "", "" ,"", ""}; /* 检查原文件与新文件名是否一致,一致就不继续进行 */ if (fileName.equals(pathname)){ System.out.println("新文件与源文件一致,请修改一处"); return; } //检查两个数组长度是否一致,不一致直接退出 if (checkLength(regex, replacment)){return;} /* 替换文件内容, fileName 源文件 pathname 新文件 regex 原字符 replacment 新字符 */ fileReadingAndWriting(fileName, pathname, regex, replacment); } /** * @param regex 数组1 * @param replacment 数组2 * @return 两个数组长度不一致返回true,一致就返回false */ private static boolean checkLength(String[] regex, String[] replacment) { if (regex.length != replacment.length){ System.out.println("regex的长度是:" + regex.length); System.out.println("replacment的长度是:" + replacment.length); return true; } return false; } /** * * @param fileName 源文件名 * @param pathname 新文件名 * @param regex 原字符 * @param replacment 新字符 */ private static void fileReadingAndWriting(String fileName, String pathname, String[] regex, String[] replacment) { for (int i = 0; i < regex.length; i++) { if (i == (regex.length - 1)){ int length = regex.length - 2; f2(pathname + length , pathname, regex[i], replacment[i]); for (int j = 0; j < regex.length; j++) { File file = new File((pathname + j)); if (file.exists()) { file.delete(); } } } else { if (i == 0){ f2(fileName, ( pathname + i ), regex[i], replacment[i]); }else { int k = i - 1; f2((pathname + k), ( pathname + i ), regex[i], replacment[i]); } } } } /** * * @param regex 被修改的文字 * @param replacement 想要的文字 * 一次只能修改一种。就要创建新文件。 */ public static void f2(String fileName, String pathname, String regex, String replacement){ try { //读取文件 FileReader fileReader = new FileReader(fileName); //把文件存到缓冲区 BufferedReader bufferedReader = new BufferedReader(fileReader); //将缓冲区文件写入指定文件中 Writer writer = new FileWriter(new File(pathname)); String str; int number = 0; //如果这一行不为空 while ((str = bufferedReader.readLine()) != null) { String str1; if (str.indexOf(regex) >= 0) { number++; str1 = str.replace(regex, replacement); } else { str1 = str; } writer.write(str1 + "\r\n"); } System.out.println("共" + number + "个" + regex + "替换为" + replacement); bufferedReader.close();//关闭缓冲区 fileReader.close();//关闭文件读取 writer.close();//关闭写入 } catch (IOException e) {//如果发生异常 e.printStackTrace();//进行异常处理 } } }