Search code examples
javaexternalbufferedreader

Stopping a BufferedReader once the external text file is empty JAVA


I've written a code here to read all the lines of a textFile and currently have an inefficient method of ending the program. I would like to read each line of the selected text file until there is nothing left in the file that hasn't been read yet and display each line to the user. I've searched up various methods however most use complex methods, I would like this to be as simple as possible without any advanced methods.

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



       }

    }

}

Solution

  • You should be using while loop instead of the for loop.

    An example

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