Java 替換資料夾下所有檔案中指定的內容
阿新 • • 發佈:2019-02-01
我的上一篇部落格提到了找到檔案中的中文。之前的程式碼還可以做一個擴充套件。可以作為一個強大的查詢功能使用。關鍵字查詢,這個功能大家可以思考一下,今後我的部落格也會去貼上這樣的關鍵字查詢的功能的程式碼,能跟大家討論分析一下。
今天的替換的功能也是基於上篇部落格的程式碼做的一個修改,談不上什麼強大,這個功能性的需求也不是很常見。今天也是跟大家做一個分享吧!
public static void main(String[] args) {
//讀取指定資料夾下的所有檔案
String filepath = "F:/wk/";//給我你的目錄資料夾路徑
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("請輸入一個目錄檔案路徑");
} else if (file.isDirectory()) {
try {
refreshFileList(filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//遞迴查詢檔案
private static void refreshFileList(String strPath) throws IOException {
File files = new File(strPath);
File[] filelist = files.listFiles();
if (filelist == null)
return;
for (int i = 0; i < filelist.length; i++) {
if (filelist[i].isDirectory()) {
refreshFileList(filelist[i].getAbsolutePath());
} else {
String filename = files.getName();//讀到的檔名
String strFileName = filelist[i].getAbsolutePath().toLowerCase();
String FileNamePath = strFileName.substring(6, strFileName.length());
//擷取檔案格式
String SufName = strFileName.substring(strFileName.lastIndexOf(".")+1,strFileName.length());
//排除不需要掃描的檔案
if(SufName.equals("rar") || SufName.equals("jpg") || SufName.equals("png") || SufName.equals("jar") || SufName.equals("doc") || SufName.equals("xls") || SufName.equals("gif") || SufName.equals("wmz")){
continue;
}
//不知為何 兩種方法判斷的時候都會吧class檔案和jar檔案當做是含有中文字元的檔案
//所以此處排除掉這class檔案和jar檔案不參與判斷
if(!"class".equals(SufName.toLowerCase())){
//開始輸入檔案流,檢查檔案
String enCode = getFileEncode(filelist[i].getAbsolutePath());
if("void".equals(enCode)){
enCode="UTF-8";
}if("windows-1252".equals(enCode)){
enCode="GBK";
}
FileInputStream fis = new FileInputStream(filelist[i].getAbsolutePath());
InputStreamReader in = new InputStreamReader(fis,enCode);
BufferedReader br = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while((line = br.readLine())!=null){
Pattern p = Pattern.compile("([\u4e00-\u9fa5]+)");
String mv = "";
//正則判斷
Matcher m = p.matcher(line);
//遍歷含有中文的行。並取出中文
while (m.find()) {
mv += m.group(0);
}
Map<String, String> map = new HashMap<String, String>();
map.put("小康", "xk");
Set<Entry<String, String>> entries = map.entrySet();
for (Entry<String, String> mapKey : entries) {
if(line.indexOf(mapKey.getKey()) != -1){ //判斷當前行是否存在想要替換掉的字元 -1表示存在
line = line.replace(mv, mapKey.getValue());//替換為你想替換的內容
}
}
strBuffer.append(line);
strBuffer.append(System.getProperty("line.separator"));//行與行之間的分割
}
br.close();
//判斷資料夾是否存在。沒有就新建資料夾
File file=new File("F:/wangkang/"+filename);
if(!file.exists())
{
file.mkdirs();
}
PrintWriter printWriter = new PrintWriter("F:/xiaokang/"+FileNamePath);//替換後輸出的檔案位置
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
System.out.println("ok 第 " + (i+1) +" 個檔案操作成功!");
}
}
}
}
//檢查檔案型別
public static String getFileEncode(String path) {
/*
* detector是探測器,它把探測任務交給具體的探測實現類的例項完成。
* cpDetector內建了一些常用的探測實現類,這些探測實現類的例項可以通過add方法 加進來,如ParsingDetector、
* JChardetFacade、ASCIIDetector、UnicodeDetector。
* detector按照“誰最先返回非空的探測結果,就以該結果為準”的原則返回探測到的
* 字符集編碼。使用需要用到三個第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar
* cpDetector是基於統計學原理的,不保證完全正確。
*/
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
/*
* ParsingDetector可用於檢查HTML、XML等檔案或字元流的編碼,構造方法中的引數用於
* 指示是否顯示探測過程的詳細資訊,為false不顯示。
*/
detector.add(new ParsingDetector(false));
/*
* JChardetFacade封裝了由Mozilla組織提供的JChardet,它可以完成大多數檔案的編碼
* 測定。所以,一般有了這個探測器就可滿足大多數專案的要求,如果你還不放心,可以
* 再多加幾個探測器,比如下面的ASCIIDetector、UnicodeDetector等。
*/
detector.add(JChardetFacade.getInstance());// 用到antlr.jar、chardet.jar
// ASCIIDetector用於ASCII編碼測定
detector.add(ASCIIDetector.getInstance());
// UnicodeDetector用於Unicode家族編碼的測定
detector.add(UnicodeDetector.getInstance());
java.nio.charset.Charset charset = null;
File f = new File(path);
try {
charset = detector.detectCodepage(f.toURI().toURL());
} catch (Exception ex) {
ex.printStackTrace();
}
if (charset != null)
return charset.name();
else
return null;
}
在結尾在加一句,這裡運用了Java基礎的小知識。Map的迴圈。
最開始做Map的迴圈是將Map的Key給取出來。然後在從Key中找Value,最近才發現Map裡面還有一個Entry介面。這個介面很好的完成一個Map集合的迴圈以及對Key-Value的取值工作。
本文中所需的Jar包在我的上一篇部落格評論中有連結。