Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: print contents of text file to screen

Tags:

java

text

io

java-7

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?

like image 882
user2151887 Avatar asked Mar 29 '13 01:03

user2151887


People also ask

How do you print to screen in Java?

You can print the text “Hello, World!” to the screen using a the method call System. out. println("Hello, World!"); .

How do you read the contents of a file into a String in Java?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.

How do I read a delimited text file in Java?

You can use BufferedReader to read large files line by line. If you want to read a file that has its content separated by a delimiter, use the Scanner class. Also you can use Java NIO Files class to read both small and large files.


1 Answers

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);    } } 
like image 122
Jiri Kremser Avatar answered Sep 21 '22 18:09

Jiri Kremser