Java: print contents of text file to screen

162,068

Solution 1

Before Java 7:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line;
 while ((line = br.readLine()) != null) {
   System.out.println(line);
 }
  • add exception handling
  • add closing the stream

Since Java 7, there is no need to close the stream, because it implements autocloseable

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Solution 2

Why hasn't anyone thought it was worth mentioning Scanner?

Scanner input = new Scanner(new File("foo.txt"));

while (input.hasNextLine())
{
   System.out.println(input.nextLine());
}

Solution 3

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Příliš žluťoučký kůň
úpěl ďábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P��li� �lu�ou�k� k��
�p�l ��belsk� �dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

Solution 4

For those new to Java and wondering why Jiri's answer doesn't work, make sure you do what he says and handle the exception or else it won't compile. Here's the bare minimum:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        for (String line; (line = br.readLine()) != null;) {
            System.out.print(line);
        }
        br.close()
    }
}

Solution 5

With Java 7's try-with-resources Jiri's answer can be improved upon:

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line = null;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Add exception handling at the place of your choice, either in this try or elsewhere.

Share:
162,068

Related videos on Youtube

user2151887
Author by

user2151887

Updated on December 07, 2020

Comments

  • user2151887
    user2151887 over 3 years

    I have a text file named foo.txt, and its contents are as below:

    this

    is

    text

    How would I print this exact file to the screen in Java 7?

    • Oliver Charlesworth
      Oliver Charlesworth about 11 years
      It sounds like you need to read text from a file. I can assure you that there is plenty of information on the web regarding reading from files in Java...
    • user2151887
      user2151887 about 11 years
      I'm telling you! I can't find this anywhere! And yes, I use Google.
    • RouteMapper
      RouteMapper about 11 years
      This past question has just the details you're looking for: stackoverflow.com/questions/2788080/reading-a-text-file-in-j‌​ava.
    • Oliver Charlesworth
      Oliver Charlesworth about 11 years
      @user2151887: So you didn't try this? google.co.uk/search?q=java+read+file
    • camickr
      camickr about 11 years
      I'm telling you! I can't find this anywhere! And yes, I use Google. I find this hard to believe. Any textbook I've ever seen or general tutorial always has a section on File I/O. Did you even look at the links provided to you on the right hand side of this page? I would think the one titled "Readig a Text File in Java" would be a good place to start.
    • fglez
      fglez about 11 years
    • jpmorris
      jpmorris over 9 years
      the OP is right. It's not that there are no guides out there, it's that they are all different. Do you use Scanner or not? Why does it take 10 lines to output a file to screen. Other langues can do it in 3. Java's horrible ability to simply output a file to screen is so bad that the HKUST Java MOOC developed it's own library because help on this issue is so fragmented.
  • kkhipis
    kkhipis over 8 years
    But what with encoding? This code depends on platform default encoding.
  • Jiri Kremser
    Jiri Kremser almost 7 years
    Right, I wanted to provide the simplest case. If you want to specify the encoding explicitly then instead of FileReader, you'd use new InputStreamReader(new FileInputStream(pathToFile), <encoding>).
  • Dem Pilafian
    Dem Pilafian almost 6 years
    ...because the question is about Java, which means the code should be overly verbose and hard on the eyes (you asked!). If you haven't tried Groovy (Java-syntax-compatible runs on JVM), I bet you'd like it.