Java之遞歸遍歷目錄,修改指定文件的指定內容

?

EditProperties.java

 1 package PropertiesOperation.Edit;
 2 
 3 import java.io.File;
 4 
 5 /**
 6  * 替換指定Porpoerties文件中的指定內容
 7  * 三個參數:
 8  * filePath:存放properties文件的目錄
 9  * srcStr:需要替換的字符串
10  * desStr:用于替換的字符串
11  * */
12 public class EditProperties {
13     private static int num = 0; // 計數變量
14     public static void main(String[] args) {
15         String filePath = "C:\\workspace\\work\\ShanDianDaiTools\\src\\main\\" +
16                 "resource\\接口測試\\app啟動次數統計接口";
17         String srcStr = "bd.test.com:8888";   //需要替換的字符串
18         String desStr = "10.15.1.200:8580";   //用于替換的字符串
19 
20         editProperties(filePath, srcStr, desStr);
21         System.out.println("總共文件數:" + num);
22     }
23 
24     public static void editProperties(String filePath, String srcStr, String desStr) {
25         File file = new File(filePath);
26 //        處理目錄情況
27         if (file.isDirectory()) {
28             File[] subFiles = file.listFiles();
29             for (File subFile : subFiles) {
30 //                子文件如果是目錄進行遞歸
31                 if (subFile.isDirectory()) {
32                     editProperties(subFile.getAbsolutePath(), srcStr, desStr);
33                 } else {
34 //                    子文件如果是文件,通過后綴名進行過濾
35                     if (subFile.getName().endsWith(".properties")) {
36                         System.out.println(subFile.getAbsolutePath());
37                         EditFile.propertiesChange(subFile.getAbsolutePath(), srcStr, desStr);
38                         num++;
39                     } else {
40                         continue;
41                     }
42                 }
43             }
44         } else {
45             // 處理單個文件情況
46             if (file.getName().endsWith(".properties")) {
47                 System.out.println(file.getAbsolutePath());
48                 EditFile.propertiesChange(file.getAbsolutePath(), srcStr, desStr);
49                 num++;
50             }
51         }
52     }
53 }

?

EditFile.java

  1 package PropertiesOperation.Edit;
  2 
  3 import java.io.*;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 
  7 /**
  8  * 修改文件中的內容* 兩種情況:1.修改文件中的指定內容;2.讀取文件并修改指定內容,復制到另一個文件中
  9  * 場景舉例:替換properties文件中的ip和端口
 10  */
 11 public class EditFile {
 12     /**
 13      * 1.修改文件中的指定內容
 14      * filePath:文件路徑
 15      * srcStr:需要替換的字符串
 16      * desStr:替換成的字符串
 17      */
 18     public static void propertiesChange(String filePath, String srcStr, String desStr) {
 19         //字符流
 20         FileReader fr = null;
 21         FileWriter fw = null;
 22         //緩沖流
 23         BufferedReader br = null;
 24         BufferedWriter bw = null;
 25 
 26         List list = new ArrayList<>();
 27         //讀取文件內容保證在list中
 28         try {
 29             fr = new FileReader(new File(filePath));
 30             br = new BufferedReader(fr);   //擴容,類似加水管
 31             String line = br.readLine();    //逐行復制
 32             while (line != null) {
 33                 //修改指定內容
 34                 if (line.contains(srcStr)) {
 35                     line = line.replace(srcStr, desStr);
 36                 }
 37                 list.add(line);
 38                 line = br.readLine();
 39             }
 40         } catch (IOException e) {
 41             e.printStackTrace();
 42         } finally {
 43             try {
 44                 //關閉流,順序與打開相反
 45                 br.close();
 46                 fr.close();
 47             } catch (IOException e) {
 48                 e.printStackTrace();
 49             }
 50         }
 51 
 52         //將list中內容輸出到原文件中
 53         try {
 54             fw = new FileWriter(filePath);
 55             bw = new BufferedWriter(fw);
 56             for (Object s : list) {
 57                 bw.write((String) s);
 58                 bw.newLine();  //換行輸出
 59             }
 60             System.out.println("文件修改成功!");
 61         } catch (IOException e) {
 62             e.printStackTrace();
 63         } finally {
 64             try {
 65                 //關閉流,順序與打開相反
 66                 bw.close();
 67                 fw.close();
 68             } catch (IOException e) {
 69                 e.printStackTrace();
 70             }
 71         }
 72     }
 73 
 74     /**
 75      * 2.讀取文件并修改指定內容,復制到另一個文件中
 76      * inputPath:修改的源文件
 77      * outputPath:修改后輸出的文件路徑
 78      * srcStr:需要替換的字符串
 79      * desStr:替換成的字符串
 80      */
 81     public static void propertiesChange(String inputPath, String outputPath, String srcStr, String desStr) {
 82         //字符流
 83         FileReader fr = null;
 84         FileWriter fw = null;
 85         //緩沖流
 86         BufferedReader br = null;
 87         BufferedWriter bw = null;
 88 
 89         try {
 90             fr = new FileReader(new File(inputPath));
 91             br = new BufferedReader(fr);   //擴容,類似加水管
 92             fw = new FileWriter(outputPath);
 93             bw = new BufferedWriter(fw);
 94 
 95             String line = br.readLine();    //逐行復制
 96             while (line != null) {
 97                 if (line.contains(srcStr)) {
 98                     line = line.replace(srcStr, desStr);
 99                 }
100                 bw.write(line);
101                 bw.newLine();  //換行輸出
102                 line = br.readLine();
103             }
104             System.out.println("文件修改成功!");
105         } catch (IOException e) {
106             e.printStackTrace();
107         } finally {
108             try {
109                 //關閉流,順序與打開相反
110                 bw.close();
111                 br.close();
112                 fw.close();
113                 fr.close();
114             } catch (IOException e) {
115                 e.printStackTrace();
116             }
117         }
118     }
119 
120 }

?

轉載于:https://www.cnblogs.com/gongxr/p/8094508.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/251242.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/251242.shtml
英文地址,請注明出處:http://en.pswp.cn/news/251242.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

學習日志---7

1.復習Linux hadoop hdfs MapReduce基礎知識 1&#xff0c;列舉linux常用命令 shutdown now reboot mkdir mkdir -p touch filename rm -r filename rm -rf filename vi filename i--->可編輯狀態 esc --> : --->wq 保存退出 q! wq! cat grep find ifconfig ping user…

javascript --- 屬性描述符

從ES5開始,所有的屬性都具備了屬性描述符 var myObject {a: 2 };Object.getOwnPropertyDescriptor(myObject, "a"); //{ // value:2, // writable: true, // 可寫 // enumerable: true, // 可枚舉 // configurble: true // 可配置 //}定義屬性…

看了嗎網址鏈接

sklearn實戰-乳腺癌細胞數據挖掘&#xff08;博主親自錄制視頻&#xff09; https://study.163.com/course/introduction.htm?courseId1005269003&utm_campaigncommission&utm_sourcecp-400000000398149&utm_mediumshare # -*- coding: utf-8 -*- ""&qu…

JMeter 性能測試進階實戰

課程簡介 本課程制作的主要目的是為了讓大家快速上手 JMeter&#xff0c;期間穿插了大量主流項目中用到的技術&#xff0c;以及結合當今主流微服務技術提供了測試 Dubbo 接口、Java 工程技術具體實施方案&#xff0c;注重實踐、注意引導測試思維、拒絕枯燥的知識點羅列、善于用…

javascript --- 混入

顯示混入: function mixin(sourceObj, targetObj){for(var key in sourceObj){ // 遍歷source中的所有屬性if(!(key in targetObj)) { // 找到targetz中沒有的屬性targetObj[key] sourceObj[key];}}return targetObj; }var Vehicle {engines: 1,iginition: function() {c…

php源碼代目錄

ext :存放動態和內建模塊的目錄&#xff0c;在這里可以找到所有的php官方虧站,并且也可以在這里編寫擴展&#xff1b; main:包含php的主要宏定義; pear: PHP擴展與應用庫; sapi:包含不同服務器抽象層的代碼; TSRM&#xff1a;Zend和PHP的"線程安全資源管理器"目錄; Z…

bzoj1231 [Usaco2008 Nov]mixup2 混亂的奶牛——狀壓DP

題目&#xff1a;https://www.lydsy.com/JudgeOnline/problem.php?id1231 小型狀壓DP&#xff1b; f[i][j] 表示狀態為 j &#xff0c;最后一個奶牛是 i 的方案數&#xff1b; 所以下一個只能是和它相差大于 k 而且不在狀態中的奶牛。 代碼如下&#xff1a; #include<iostr…

JavaScript高級程序設計閱讀筆記

2020-11-15 通過初始化指定變量類型 數字-1 對象null和null的比較&#xff08;不理解&#xff09;使用局部變量將屬性查找替換為值查找&#xff08;算法復雜度&#xff09;循環的減值迭代&#xff0c;降低了計算終止條件的復雜度switch快多個變量聲明逗號隔開使用數組和對象字面…

jquery --- 監聽input框失效

使用juery監聽Input輸入的變化,并且封裝起來,如下: // html <input type"text" id‘myinput1’ /> // js function formOnById(id){let dom # id;$(dom).bind(input propertychange,()>{let item $(dom).val;console.log(item);} } formOnById(myinp…

windows任務計劃程序 坑

轉載于:https://www.cnblogs.com/kaibindirver/p/8109041.html

第三篇:函數之嵌套

1 #函數的嵌套調用&#xff1a;在調用一個函數的時&#xff0c;其內部的代碼又調用其他的函數2 # def bar():3 # print(from bar)4 #5 # def foo():6 # print(from foo)7 # bar()8 #9 # foo() 10 11 12 # def max2(x,y): 13 # if x > y: 14 # ret…

vue路由權限(結合服務端koa2)

gitee地址 一、項目初始化 vue create manager-admin // 創建vue項目// 管理員權限安裝 cnpm i -S koa2 // 下載koa2依賴 cnpm install --global koa-generator // 下載框架 koa-generator koa2 manager-server // 創建項目 cd manager-server // 進入項目 npm install // 安…

javascript --- 類、class、事件委托的編程風格

類風格: // 父類 function Widget(width, height) {this.width width || 50;this.height height || 50;this.$elem null; } Widget.prototype.render function($where) {if(this.$elem) {this.$elem.css({width: this.width "px",height: this.height "p…

在線獲取UUID

http://fir.im/udid轉載于:https://www.cnblogs.com/mtjbz/p/8116576.html

堆和堆排序

堆和優先隊列 普通隊列&#xff1a;FIFO&#xff0c;LILO 優先隊列&#xff1a;出隊順序和入隊順序無關&#xff0c;和優先級相關。一個典型應用就是操作系統中。動態選擇優先級高的任務執行 堆的實現 最典型的堆就是二叉堆&#xff0c;就像是一顆二叉樹。這個堆的特點&#xf…

ES5-1 發展史、ECMA、編程語言、變量、JS值

1. 5大主流瀏覽器及內核&#xff08;自主研發&#xff09; 瀏覽器內核IEtridentChromewebkit blinkSafariwebkitFirefoxgeckoOperapresto 2. 瀏覽器的歷史 和 JS誕生 1989-1991 WorldWideWeb&#xff08;后來為了避免與萬維網混淆而改名為Nexus&#xff09;是世界上第一個網頁…

javascript --- 使用對象關聯簡化整體設計

在某個場景中,我們有兩個控制器對象: 1.用來操作網頁中的登錄表單; 2.用來與服務器進行通信. 類設計模式 // 把基礎的函數定義在名為Controller的類中,然后派生兩個子類LoginController和AuthController. // 父類 function Controller() {this.errors []; } Controller.prot…

javascript --- polyfill中幾個常用方法

ES6中,新增了許多有用的方法,下面分享幾個ES6之前得版本寫的polyfill Number.EPSILON: // 機器精度,并判斷2個數是否相等 if(!Number.EPSILON){Number.EPSILON math.pow(2, -52); }function numberCloseEnoughToEqual(n1, n2) {return Math.abs(n1 - n2 ) < Number.EPSIL…

[Usaco2010 Nov]Visiting Cows

題目描述 經過了幾周的辛苦工作,貝茜終于迎來了一個假期.作為奶牛群中最會社交的牛,她希望去拜訪N(1<N<50000)個朋友.這些朋友被標號為1..N.這些奶牛有一個不同尋常的交通系統,里面有N-1條路,每條路連接了一對編號為C1和C2的奶牛(1 < C1 < N; 1 < C2 < N; C1…

ES5-2 語法、規范、錯誤、運算符、判斷分支、注釋

1. 錯誤 MDN錯誤列表 Uncaught SyntaxError: Unexpected token ) // 語法錯誤 Uncaught ReferenceError: a is not defined // 引用錯誤等類型 Uncaught TypeError: Cannot read property toString of null出現一個語法錯誤&#xff0c;則一行代碼都不會執行&#xff08;檢查…