2013-04-07 74 views
-1

我正在嘗試讀取文件,但只想讀取前5行,然後將它們打印在屏幕上。不知道如何正確地迭代循環。以下代碼只是輸出整個文件。我還需要檢查該文件在廁所中是否少於6行。任何提示不勝感激。用fileReader只讀第5行

import java.io.*; 

public class File_Reader 
{ 
public static void main(String [] args) throws IOException 
{ 
    // int counter=0;String str; 
    String fileName = "MyFile.txt"; 

    String line = null; 


     FileReader fileReader = 
      new FileReader(fileName); 


     BufferedReader bufferedReader = 
      new BufferedReader(fileReader); 

     while((line = bufferedReader.readLine()) != null) { 
      System.out.println(line); 
     } 

     bufferedReader.close();   

} 
} 
+2

你爲什麼不只是增加一個計數器來while循環?它已經每行執行一次。 – FoolishSeth 2013-04-08 00:01:24

+2

因此,爲'(int i = 1; i <= 5; i ++)'改變'while'真的很難... – 2013-04-08 00:01:43

+0

爲什麼while循環循環直到'BufferedReader'到達最後,如果你想要它停在五號線?只需數線。 – Justin 2013-04-08 00:01:46

回答

3

這只是一個循環,直到迭代了5倍

import java.io.*; 


    public class File_Reader 
    { 
    public static void main(String [] args) throws IOException 
    { 
     // int counter=0;String str; 
     String fileName = "MyFile.txt"; 

     String line = null; 

      BufferedReader bufferedReader = 
       new BufferedReader(new FileReader(fileName)); 

      int i = 0; 
      try { 
       //print first 5 lines or all if file has less than 5 lines 
       while(((line = bufferedReader.readLine()) != null) && i < 5) { 
        System.out.println(line); 
        i++; 
       } 
      } 
      finally { 
       bufferedReader.close();   
      } 

     } 
    }