2012-03-03 4 views
0

내가 만든 방법으로 전체 텍스트 파일을 읽으려고합니다. 텍스트 파일의 모든 줄은 내가 원했던 것처럼 출력되지만, 인쇄 될 때 null로 나타나는 파일의 마지막 줄은 출력됩니다. 그들은 방법은 그래서이 줄 거예요 전혀 나타나지 "널 (null)이"어떻게 코드를 작성 것이라고 말했습니다 하단에 여분의 줄을 추가 제외시켰다해야으로 파일의 마지막 읽기 라인이 null로 인쇄됩니다.

private void readFile(String Path) throws IOException{ 
    String text = ""; //String used in the process of reading a file 

    //The file reader 
    BufferedReader input = new BufferedReader(
      new FileReader(Path)); 

    //Creating a new string builder. 
    StringBuilder stringBuilder = new StringBuilder(); 

    while(text != null) 
    { 
     //Read the next line 
     text = input.readLine(); 

     stringBuilder.append(text); //Adds line of text into the String Builder 
     stringBuilder.append(newLine); //Adds a new line using the newLine string 
    } 

    //Sets the text that was created with the stringBuilder 
    SetText(stringBuilder.toString()); 
} 

모든 파일

100 % 인쇄됩니다?

답변

1

루프 종료 조건의 위치가 잘못되었습니다.

while ((text = input.readLine()) != null) { 
    stringBuilder.appendText(text) 
    ... 
4

이 작업을 변경할 수 있습니다

while(text != null) 
    { 
     //Read the next line 
     text = input.readLine(); 

     // ... do stuff with text, which might be null now 
    } 

를 하나이에 :

while((text = input.readLine()) != null) 
    { 
     // ... do stuff with text 
    } 

나이 :

while(true) 
    { 
     //Read the next line 
     text = input.readLine(); 
     if(text == null) 
      break; 

     // ... do stuff with text 
    } 

나이 :

text = input.readLine(); 
    while(text != null) 
    { 
     // ... do stuff with text 

     //Read the next line 
     text = input.readLine(); 
    } 

을 원하십니까?

+0

또는 텍스트 초기화 = input.readLine(); 한 번 루프 전에, 그리고 다시 한 번 루프 몸체의 끝에서. – jacobm

+1

@jacobm : True. . . 하지만 누구나 실제로 그것을 선호합니까? – ruakh

+0

영어로 진행되는 일을 설명하는 방법에 직접적으로 대응하기 때문에 실제로는 약간 선호합니다. (비록 두 번 같은 줄을 반복해야만한다.) – jacobm

0

쉽게 이해할 수있는 청소기 솔루션을 얻을 것이다 미리 읽기 사용 :

text = input.readLine(); 

while(text != null) 
    { 
     stringBuilder.append(text); //Adds line of text into the String Builder 
     stringBuilder.append(newLine); //Adds a new line using the newLine string 

     //Read the next line 
     text = input.readLine(); 
    } 

미리 읽기의 원리를 사용하여, 당신은 거의 항상 나쁜 종료 조건을 피할 수 있습니다.