2012-06-23 5 views
-1

"Sample.text"라는 텍스트 파일이 있습니다. 그것은 여러 줄을 포함하고 있습니다. 이 파일에서 특정 문자열을 검색했습니다. 일치하는 파일이 있거나 파일에서 찾으면 전체 줄을 인쇄해야합니다. 문자열을 검색하는 것은 줄의 중간에 있습니다. 또한 문자열 file.Also 텍스트 파일에서 문자열을 읽은 후 문자열을 추가하려면 문자열 버퍼를 사용하여 너무 큰 size.so 줄 단위로 반복 할 싶지 않아요. 이자바에서 문자열 일치 발견시 파일의 전체 줄을 인쇄하는 방법

+0

내가 문자열로 노력했다. 그러나 적절한 값을 반환하지 않습니다. – santro

+0

이 질문을 참조하십시오 : http://stackoverflow.com/questions/6222659/java-grep-library –

답변

5

당신은 Apache Commons IO

작은 샘플에서 Fileutils의와 함께 할 수있는 수행 방법 : 우리는 또한 파일에서 일치하는 문자열이나 패턴 정규 표현식을 사용할 수 있습니다

StringBuffer myStringBuffer = new StringBuffer(); 
    List lines = FileUtils.readLines(new File("/tmp/myFile.txt"), "UTF-8"); 
    for (Object line : lines) { 
     if (String.valueOf(line).contains("something")) { 
      myStringBuffer.append(String.valueOf(line)); 
     } 
    } 
+0

답장을 보내 주셔서 감사합니다. 문자열을 검색하는 것은 줄의 중간에 있습니다. 또한 문자열 file.Also 텍스트 파일에서 문자열을 읽은 후 문자열을 추가하려면 문자열 버퍼를 사용하여 너무 큰 size.so 줄 단위로 반복 할 싶지 않아요. – santro

+0

내가 의심하는 질문에서 그는 문자열이 줄에 들어 있는지 알고 싶어합니다. 어쩌면'startsWith'를'contains'로 바꾸기를 원할 수도 있습니다. – atamanroman

+0

@santro 방금 편집했습니다.) –

0

.

샘플 코드 :

import java.util.regex.*; 
import java.io.*; 

/** 
* Print all the strings that match a given pattern from a file. 
*/ 
public class ReaderIter { 
    public static void main(String[] args) throws IOException { 
    // The RE pattern 
    Pattern patt = Pattern.compile("[A-Za-z][a-z]+"); 
    // A FileReader (see the I/O chapter) 
    BufferedReader r = new BufferedReader(new FileReader("file.txt")); 
    // For each line of input, try matching in it. 
    String line; 
    while ((line = r.readLine()) != null) { 
     // For each match in the line, extract and print it. 
     Matcher m = patt.matcher(line); 
     while (m.find()) { 
     // Simplest method: 
     // System.out.println(m.group(0)); 
     // Get the starting position of the text 
     int start = m.start(0); 
     // Get ending position 
     int end = m.end(0); 
     // Print whatever matched. 
     // Use CharacterIterator.substring(offset, end); 
     System.out.println(line.substring(start, end)); 
     } 
    } 
    } 
} 
관련 문제