2014-04-04 3 views
0

파일에서 데이터를 읽으려면 다음 코드를 사용하고 있지만 줄의 색인을 찾을 수 없습니까?줄의 색인을 찾는 방법?

public static ArrayList<String> searchInFile(String word) { 


    ArrayList<String> result = new ArrayList<String>(); 
    FileReader fileReader = null; 
    try { 
     fileReader = new FileReader(new File("input.txt")); 
    } catch (FileNotFoundException e1) { 
     System.err.println("File input.txt not found!"); 
     e1.printStackTrace(); 
    } 

    BufferedReader br = new BufferedReader(file); 
    String line; 
    try { 
     while ((line = br.readLine()) != null) { 
      if (line.contains(word)) { 
       result.Add(line); 
      } 
     } 

    } catch (IOException e) { 
     System.err.println("Error when processing the file!"); 
     e.printStackTrace(); 
    } finally { 
     if (br != null) { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       System.err.println("Unexpected error"); 
       e.printStackTrace(); 
      } 
     } 

    } 
    return result; 
} 

그래서 어떻게 색인의 색인을 찾을 수 있습니까 ??

답변

2

라인 인덱스를 추적 할 수있는 카운터 정수 변수를 만들어야합니다.

int ctr =0; 
    while ((line = br.readLine()) != null) { 
     if (line.contains(word)) { 
      result.Add(line); 
     } 
     ctr++; 
    } 

희망 하시겠습니까?

+0

네, 그게 도움이되지만 내가 다른 puropose에 대한 라인의 인덱스를 발견하고 싶습니다 나는 라인의 인덱스를 찾을 수 있습니까 ??? – user3271822

+0

나는 BufferedReader로 할 수 없다고 믿었다. 파일을 읽을 때, 얼마나 많은 라인이 있는지를 알 수있는 방법이 없다. (카운터를 사용하지 않는다면) while 루프가 사용되는 이유는 파일의 끝까지 반복 될 것이다. 확실하지 않지만 BufferedReader를 사용하지 않고 필요한 것을 얻을 수있는 프레임 워크가있을 수 있습니다. – lorraine

관련 문제