2012-08-09 2 views
2

파일 내용에 정규 표현식을 사용하는 방법. 나는 파일 그룹을 가지고 있는데, 나는 모든 파일에서 문자열을 검색하고 모든 파일에서 바꾸고 싶다.파일 내용에 자바 정규식

누구든지 나를 도와 줄 수 있습니까? 위장 위치는 다음과 같습니다.

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'를 사용하는 3. 루프 동적, 쉽게 만들 수 있을까요? 아 ... 윈도우 박스에있는 것처럼 보입니다. – Nishant

+0

대용량 파일에서는 정규 표현식이 작동하지 않습니다. 그들의 특성상 Regexps는 재귀 적이며, regexp로 대량의 데이터를 처리 할 때 StackOverflow 예외가 발생합니다. –

답변

4

궤도가 오른 것처럼 보입니다. 파일에서 대체 할 & 프레임 워크를 알 수 없습니다. 나는 당신이 검토 할 수있는 몇 가지 다른 팁을 달았습니다.

누락 된 마지막 단계는 OutputWriter 또는 유사한 출력기를 추가하는 것입니다. 파일 내용을 읽은 다음 내용물이 &으로 바뀌 었는지 확인하고 변경 사항이 적용되었는지 여부를 확인해야합니다. 그렇다면 파일을 출력하십시오.

기타 의견 : 당신이 .listFiles() 2. 효율성을 위해 for 루프 외부에서 패턴을 컴파일 사용하는 경우 1. 당신은 listofFiles[i].isFile()을 할 필요가 없습니다.

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

초보자이기 때문에 코드를 제공해 주시겠습니까 –

+0

샘플이 업데이트되었습니다. Pattern이나 Matcher를 사용하지 않는다면 어떤 패턴을 사용할지 결정할 수 있습니다. BOth는 좋지만 Pattern & Matcher가 더 좋습니다. –

+0

위의 코드에서 파일 확장명을 지정하는 위치는 –