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?
You can print the text “Hello, World!” to the screen using a the method call System. out. println("Hello, World!"); .
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.
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.
Before Java 7:
BufferedReader br = new BufferedReader(new FileReader("foo.txt")); String line; while ((line = br.readLine()) != null) { System.out.println(line); }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With