Reading and Writing from & to files are another important part of any programming language.
Without much history, lets learn how to Read files.
Let's assume you want to read a file on your desktop named
test.txt
and your java program also is on your desktop.
text.txt
has the following lines:
"Hello World of Java"
"I am reading a file"
import java.io.*; class ReadFile{ public static void main(String[] args){ File file = new File("text.txt"); try(FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);){ String line; while((line = br.readLine()) != null){ System.out.println(line); } }catch(IOException ioe){ System.out.println(ioe.getMessage()); } } }
To run it in the terminal, type
// -> Java 10 and below javac ReadFile.java java ReadFile // -> Java 11 and above (no need to compile it first) java ReadFile.java // output Hello World of Java I am reading a file
Time to break it down a little.
File file = new File("text.txt"); // The File class does not create a file, // It only holds the location/path of the file. //eg: File file = new File("path-to-file");
String line; while((line = br.readLine()) != null) ... // can also be written as String line = br.readLine(); while(line != null){ System.out.println(line); line = br.readLine(); // reads the line again }
try(FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);){ ...
This try(...){
closes the FileReader
and BufferedReader
automatically for us. Read more about try-with-resource in my other post;
Thanks for reading. Next up, we will learn how to write/create a file.
Please leave your comments and any questions you might have.
Top comments (0)