2017-12-10 18 views
0

파일의 단어를 스트림으로 읽으려고 시도하고 단어 "the"가 파일에 나타나는 횟수를 계산하려고합니다. 나는 단지 스트림으로 이것을하는 효율적인 방법을 알아낼 수 없다.스트림에서 파일에서 단어 읽기

예 : 파일에 "강가에서 뛰었습니다."와 같은 문장이 포함 된 경우 출력이 내가 지금까지 시도했습니다

public static void main(String[] args){ 

    String filename = "input1"; 
    try (Stream<String> words = Files.lines(Paths.get(filename))){ 
     long count = words.filter(w -> w.equalsIgnoreCase("the")) 
       .count(); 
     System.out.println(count); 
    } catch (IOException e){ 

    } 
} 
+2

지금까지 시도한 코드 샘플을 제공해주십시오. 그렇게하면 더 효과적으로 당신을 도울 수 있습니다. – Ivonet

답변

0

당신은이 목적을 위해 자바의 StreamTokenizer을 사용할 수있는 것입니다 2

될 것이다.

import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StreamTokenizer; 
import java.io.InputStreamReader; 
import java.nio.charset.StandardCharsets; 

public class Main { 

    public static void main(String[] args) throws IOException { 
     long theWordCount = 0; 
     String input = "The boy jumped over the river."; 
     try (InputStream stream = new ByteArrayInputStream(
      input.getBytes(StandardCharsets.UTF_8.name()))) { 
     StreamTokenizer tokenizer = 
      new StreamTokenizer(new InputStreamReader(stream)); 
      int tokenType = 0; 
      while ((tokenType = tokenizer.nextToken()) 
       != StreamTokenizer.TT_EOF) { 
       if (tokenType == StreamTokenizer.TT_WORD) { 
        String word = tokenizer.sval; 
        if ("the".equalsIgnoreCase(word)) { 
         theWordCount++; 
        } 
       } 
      } 
     } 
     System.out.println("The word 'the' count is: " + theWordCount); 
    } 
} 
0

그냥 선 이름은 라인없는 단어의 Files.lines 반환 스트림을 제안합니다. 당신이 단어를 반복하려는 경우 당신이 정말로 당신이 각 행을 분할 할 수 있습니다 스트림을 사용하고 그 단어에 스트림을 매핑 할 경우에 나는 당신이

Scanner sc = new Scanner(new File(fileLocation)); 
while(sc.hasNext()){ 
    String word = sc.next(); 
    //handle word 
} 

같은 Scanner을 사용할 수 있습니다

try (Stream<String> lines = Files.lines(Paths.get(filename))){ 
    long count = lines 
      .flatMap(line->Arrays.stream(line.split("\\s+"))) //add this 
      .filter(w -> w.equalsIgnoreCase("the")) 
      .count(); 
    System.out.println(count); 
} catch (IOException e){ 
    e.printStackTrace();//at least print exception so you would know what wend wrong 
} 

BTW 당신이 shouldn 빈 캐치 블럭을 남겨 두지 마라. 적어도 문제가 발생하면 더 많은 정보를 얻을 수 있도록 예외를 던져라.

+0

.split 명령의 정규 표현식은 단락 사이의 구분과 같이 줄 바꿈 문자를 따라 분할됩니까? –

+0

@AddisonWaege 가능성이 큽니다. '\ s'는 넓은 범위의 공백을 나타내며 일반적으로 이러한 종류의 작업에는 충분합니다. 그것을 시험하면 알게 될 것입니다. – Pshemo

0

스트림 리더를 사용하여 단어 수를 계산하십시오.