How do you read a text file in Java? If this is your answer, then its bad:
try (var inputFile = new FileReader("/Users/ganesh/limerick.txt")) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
}
Two problems are:
- It is verbose — quite a few lines of code for something as simple as reading the contents of a text file!
- It is low-level — like why do we have to use a int (not char, mind you!) and check with -1 for end of file and cast it back to char for printing it in console
A better way is to use the stream’s approach as in:
Files.lines(Paths.get("/Users/ganesh/limerick.txt"))
.forEach(System.out::println);
The Files.lines method reads a file and iterates over each line in the read file as a stream. The forEach consumes each string and we are printing it in the console.
This approach is much better than the earlier code because it is
- Concise and sweet — this code is just onto the task of reading a file, iterating over it and printing it in the console. Brief and to-the-point.
- High-level — easier code to read than the previous low-level code
Here is the video of writing this code in IntelliJ IDEA — hope you’ll find it useful! https://youtu.be/EIj8XD460ck