2012-08-09 21 views
2

如何在文件內容中使用正則表達式。我有一組文件,我想在所有文件中搜索一個字符串並替換所有文件。java在文件內容中的正則表達式

有人可以幫我嗎?如下:

package com.java.far; 
import java.io.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class ReplaceAll { 

    public static void main(String[] args)throws IOException { 

     Runtime r=Runtime.getRuntime(); 
     System.out.println(r.freeMemory()); 

     String path="D:\\JOBRELATED\\FAR"; 
     String files; 
     File folder=new File(path); 
     File[] listofFiles=folder.listFiles(); 
     for (int i = 0; i < listofFiles.length; i++) { 
      if (listofFiles[i].isFile()) { 
       files=listofFiles[i].getName(); 
       if(files.endsWith("tex")){ 
       System.out.println(files); 

       BufferedReader br=new BufferedReader(new FileReader("D:\\JOBRELATED\\FAR\\"+files)); 
       String line; 
       while((line=br.readLine())!=null){ 
       Pattern p=Pattern.compile("Diamond in History and Research"); 
       Matcher m=p.matcher(line); 
       int count=0; 
       while (m.find()) { 
        count++; 
        //System.out.println(m.start() +"\t"+ count); 
        System.out.println(line); 
        m.replaceAll("abc"); 


       } 
       } 

      } 
      } 
     } 


    } 
} 
+0

是沒可能只使用'sed'?啊......看起來像你在Windows上。 – Nishant 2012-08-09 05:26:52

+0

請注意,正則表達式不適用於大文件。正則表達式本質上是遞歸的,在使用正則表達式處理大塊數據時,會出現StackOverflow異常。 – 2012-08-09 06:09:13

回答

4

看起來像你在正確的軌道;我不知道在文件中會找到替換&的框架。我已經提供了一些其他提示,您可以在其中查看。

您缺少的最後一步是添加一個OutputWriter或類似的輸出器。一旦你閱讀了文件內容,檢查它是否包含匹配&取代它,你應該做一個布爾檢查是否進行了更改。如果是,輸出文件。

其他評論: 1.你不會需要做listofFiles[i].isFile()如果你使用.listFiles() 2.編譯for循環效率之外你的格局。 3.使用動態的for循環,可能更容易:for(final File file : listofFiles)

例子:

final File[] files = new File(".").listFiles(); 
    final Pattern pattern = Pattern.compile(".*a.*"); 
    for(final File file : files) { 
     System.out.println(file.getName()); 
     final BufferedReader reader = new BufferedReader(new FileReader(file)); 
     final StringBuilder contents = new StringBuilder(); 
     while(reader.ready()) { 
      contents.append(reader.readLine()); 
     } 
     reader.close(); 
     final String stringContents = contents.toString(); 
     if(stringContents.toString().matches(".*a.*")) { 
      stringContents.replaceAll("a", "b"); 
      final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); 
      writer.write(stringContents); 
      writer.close(); 
     } 
    } 
+0

你可以提供我的代碼,因爲我是一個初學者 – 2012-08-09 05:30:34

+0

以上更新示例。因爲我沒有使用模式或匹配器,你可以決定使用它的方式。 BOth很好,Pattern&Matcher可能更好。 – 2012-08-09 05:40:13

+0

但在哪裏給上述代碼的文件擴展名 – 2012-08-09 06:42:08