IO流处理文件
一、使用场景
遍历文件夹下的所有.html与.shtml文件,将其中的http://www.xxx.cn/替换成//www.xxx.cn/,并且记录修改的总链接数,记录修改的链接所在文件夹名以及所在行。
二、使用要求
因为此段代码只能处理非图片的文件,所以要求输出目录和处理目录需要一致,否则需要要求文件非.jpf,.gif类型的数据。
三、代码
-
前端
代码
<button type="button" id="btn2">替换数据</button> /*测试替换数据测试*/ $('#btn2').click(function (){ $.ajax({ type:"GET", url:"/api/processOfData.json", async:true, // 异步,默认开启,也就是$.ajax后面的代码是不是跟$.ajx里面的代码一起执行 cache:true, // 表示浏览器是否缓存被请求页面,默认是 true dataType:"json", // 返回浏览器的数据类型,指定是json格式,前端这里才可以解析json数据 success:function(data){ }, error:function(){ console.log("发生错误") alert("发生错误"); }, complete:function(){ console.log("ajax请求完事,最终操作在这里完成") } }); });
说明
为了方便,直接在现有的项目的页面上加了个按钮,点击按钮触发Ajax请求后台
-
后台
说明
1.总链接数allNuM需要定义成静态变量,初始化常量池,而且每次点击需要将其数量初始化零,否则多次点击按钮会在上次总数上累加修改的总链接数; 2.new FileWriter(输出路径名,true)其中true的意思是不覆盖上次输出的内容; 3.File outPath = new File(file[i].getParent().replace("D:", "E:"));这里是定义修改之后的文件夹输出文件夹目录,建议不修改,因为有.jpg等文件会直接丢失(重点); 4.FileWriter printWriter2 = new FileWriter("E:\\dataLog"+"\\"+"datalog.txt", true); =》操作日志目录
代码
public static int allNum;//记录修改的总链接数 @GetMapping("processOfData.json") @ResponseBody public JSONObject processOfData(HttpServletRequest request,HttpServletResponse response) throws IOException { allNum=0;//因为该变量初始化到常量池内,每次点击需要重新归零 JSONObject jsonObject = new JSONObject(); File f = new File("D:/newData/history1_20211028.tar.zip");//D:/bakData/history1_20211028.tar.zip print(f, 0); FileWriter printWriter3 = new FileWriter("E:\\dataLog"+"\\"+"datalog.txt", true); // 替换后输出文件路径 String content = "修改的总链接数:"+allNum; printWriter3.write(content.toCharArray()); //又一次写入 printWriter3.flush(); printWriter3.close(); return jsonObject; } /** * 遍历目录 * * @param f * @param len */ public static void print(File f, int len) { File[] file = f.listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) { //推断是否目录 print(file[i], len + 1); } // 为防止输出文件覆盖源文件,所以更改输出盘路径 也可自行设置其它路径 // File outPath = new File(file[i].getParent().replace("D:", "E:")); File outPath = new File(file[i].getParent()); File readfile = new File(file[i].getAbsolutePath()); if (!readfile.isDirectory()) { String filename = readfile.getName(); // 读到的文件名称 String suffix = filename.substring(filename.lastIndexOf(".") + 1); //只有后缀名为.html和.shtml文件需要修改文件内容 if(suffix.indexOf("html") != -1||suffix.indexOf("shtml") != -1){ String absolutepath = readfile.getAbsolutePath(); // 文件的绝对路径 int numOfLj = readFile(absolutepath, filename, i, outPath); // 调用 readFile allNum+=numOfLj; } } } } /** * 读取目录下的文件 * @return */ public static int readFile(String absolutepath, String filename,int index, File outPath) { try { //是否满足修改条件,默认不满足 Boolean flag = false; //是否修改当前行,默认没修改 Boolean flag2 = false; //记录行数 int lineNum = 0; //记录修改链接总数 int totleCounts = 0; BufferedReader bufReader = new BufferedReader(new InputStreamReader( new FileInputStream(absolutepath), "utf-8")); // 数据流读取文件 StringBuffer strBuffer = new StringBuffer(); StringBuffer strBuffer2 = new StringBuffer();//记录文件修改的行数以及具体的链接名 String newStr = "//www.cas.cn"; String oldStr = "http://www.cas.cn"; // String oldStr2 = "https:"; for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) { //记录行数 lineNum++; if ((temp.indexOf(oldStr) != -1)) { // 推断当前行是否存在想要替换掉的字符 flag=true;//满足条件 flag2=true;//满足打印行数条件 //一行出现多个相同字符串 int oldLength=temp.toString().length(); temp = temp.replace(oldStr, newStr); // 此处进行替换 int newLength=temp.toString().length(); int count=0; count = (oldLength-newLength)/5; totleCounts+=count;//记录每个文件修改链接总数 } strBuffer.append(temp); if(flag2) {//打印修改链接所在的行数 strBuffer2.append(lineNum + ","); flag2=false;//还原 } strBuffer.append(System.getProperty("line.separator")); // 换行符 } bufReader.close(); if (outPath.exists() == false) { // 检查输出目录是否存在,若不存在先创建 outPath.mkdirs(); // System.out.println("已成功创建输出目录:" + outPath); } PrintWriter printWriter = new PrintWriter(outPath + "\\" + filename, "utf-8"); // 替换后输出文件路径 printWriter.write(strBuffer.toString().toCharArray()); //又一次写入 printWriter.flush(); printWriter.close(); // System.out.println("第 " + (index + 1) + " 个文件 " + absolutepath + " 已成功输出到 " + outPath + "\\" + filename); //log日志输出 if(flag) { System.out.println("文件:" + absolutepath+"已被修改"); FileWriter printWriter2 = new FileWriter("E:\\dataLog"+"\\"+"datalog.txt", true); // 替换后输出文件路径 String content = "文件名:"+absolutepath+",被修改链接所在行:"+strBuffer2.toString()+"\n"; printWriter2.write(content.toCharArray()); //又一次写入 printWriter2.flush(); printWriter2.close(); } //返回每个文件修改的链接总数 return totleCounts; } catch (Exception e) { e.printStackTrace(); } return 0; }