user2151887 user2151887 - 7 months ago 21
Java Question

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?

Answer

Before Java 7:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line = null;
 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 = null;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}