Search code examples
javatextiojava-7

Java: print contents of text file to screen


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?


Solution

  • 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);
       }
    }