Reading and displaying data from a .txt file

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));

Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:

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

If your file is strictly text, I prefer to use the java.util.Scanner class.

You can create a Scanner out of a file by:

Scanner fileIn = new Scanner(new File(thePathToYourFile));

Then, you can read text from the file using the methods:

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file

And, you can check if there is any more text left with:

fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file

Once you have read the text, and saved it into a String, you can print the string to the command line with:

System.out.print(aString);
System.out.println(aString);

The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.


In general:

  • Create a FileInputStream for the file.
  • Create an InputStreamReader wrapping the input stream, specifying the correct encoding
  • Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
  • Read until there's no more data (e.g. readLine returns null)
  • Display data as you go or buffer it up for later.

If you need more help than that, please be more specific in your question.


I love this piece of code, use it to load a file into one String:

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();