2017-04-20 8 views
0

여기 textFile의 모든 행을 읽는 코드를 작성했으며 현재 프로그램을 종료하는 데 비효율적 인 방법이 있습니다. 아직 읽지 않은 파일에 아무것도 남아 있지 않을 때까지 선택한 텍스트 파일의 각 줄을 읽고 각 줄을 사용자에게 표시하려고합니다. 그러나 여러 가지 방법을 사용하여 검색 한 적이 있지만 대부분은 복잡한 방법을 사용하므로 가능한 한 간단하게 고급 방법이 필요하지 않습니다.외부 텍스트 파일이 비어있는 경우 BufferedReader 중지 JAVA

package textfilereader; 

import java.io.*; 
import java.util.Scanner; 
import java.io.FileReader; 
import java.io.IOException; 

public class TextFileReader 
{ 


    public static void main(String[] args) throws IOException 
    { 

     Scanner scanner = new Scanner (System.in); 

     System.out.println("Please enter the name of the text document you would like to open"); 
     System.out.println("For example, 'userName.txt'"); 
     String textFile = scanner.nextLine(); 

     try (BufferedReader readFile = new BufferedReader (new FileReader("c:/Users/Nicholas/Desktop/"+textFile))) 
     { 


      System.out.println("Contents of the file: "+textFile); 

      for (int i = 0; i < 100; i++) 
      { 
       String line = readFile.readLine(); 
       System.out.println(line); 

       if (line.equals(null)) 
        { 
         i = 100; 
        //my inefficient method is currently to continue the loop 
        //if "i" is less than 100, this value can be any value 
        //if the line is a null it will set i to be 100 so the 
        //loop will stop 
        } 
      } 

      readFile.close(); 



     } 

    } 

} 
+3

'동안 ((라인 = readFile.readLine() = NULL) {...}'- 난 강력하게 당신이 [기본 IO]에서 봐 가지고 제안 (HTTPS :!//docs.oracle.com/javase/tutorial/essential/io/) 및 [BufferedReader # readLine'에 대한 JavaDocs] (https://docs.oracle.com/javase/8/docs/api/java/io/)를 참조하십시오. BufferedReader.html # 작성한 Readline--) – MadProgrammer

+1

'동안 ((라인 = readFile.readLine())! = NULL) {...}' – davidxxx

+0

가, 감사합니다를 –

답변

1

당신은 while 루프 대신 for 루프를 사용한다.

// ... 
String line = null; 
while ((line = readFile.readLine()) != null) { 
      System.out.println(line); 
} 
readFile.close(); 
// ... 
+1

이 작동합니다 고마워요,하지만 내가 왜 당신이 문자열 라인 = null을 설정에 대한 설명을하고 싶습니다 –

+0

이 경우에는 필요하지 않지만 더 명시 적입니다. – JiriS