簡體   English   中英

文件內容中的Java正則表達式

[英]java regular expression in a file content

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

有人可以幫我嗎? 的原因是:

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");


                }
                }

            }
            }
        }


    }
}

看起來您在正確的軌道上; 我不知道會在文件中查找和替換的框架。 我提出了一些其他技巧,您可以在下面進行回顧。

您缺少的最后一步是添加一個OutputWriter或類似的輸出器。 讀取文件內容后,檢查其中是否包含匹配項並替換了該文件,您應進行布爾檢查是否進行了更改。 如果是這樣,則輸出文件。

其他注釋:1.如果您使用的是listofFiles[i].isFile()則無需執行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();
       }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM