-1

我正在尝试读取文件,但只想读取前 5 行,然后将它们打印在屏幕上。不知道如何用循环正确地迭代它。以下代码仅打印整个文件。我还需要检查文件在 loo 中是否少于 6 行。非常感谢任何提示。

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();         

}
}
4

1 回答 1

4

这只是一个循环,直到它迭代 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();         
            }

        }
    }
于 2013-04-08T00:03:43.943 回答