This example shows how to read the contents of a file line by line.
By using the BufferedReader class we can read line-by-line without having to worry about
linebreaks. We just call it’s readLine() method for as long as it doesn’t return null, which it does when it has reached the end of the file.
Don’t forget to call close() on the BufferedReader when done.
Here’s an example that can solve the problem to sort rows in a file based upon a certain value on each row.
Say for example that we have a text file which has information about employees. The first value is employee nr, the second is the name of the employee and the third value is the salary.
The values on each row are separated by a comma. In this code example we are going to sort the list ascending on the salary value.
This is what the file ’employees.txt’ looks like:
This example shows how to read input from console using the BufferedReader class. The BufferedReader has a neat method called readLine() that reads all the input characters into a string when the user hits the Enter button instead of reading byte by byte.
This example takes the input string and parses it into a variable of type Double and then prints out the square root of that number.
This is the code:
For reading text from a file it’s better to use a Reader class instead of a InputStream class since Reader classes have the purpose of reading textual input.
In this example we use the BufferedReader class to read text from a file line by line using it’s readLine method.
It is possible to read the data the same way as with the BufferedInputStream using either a byte array or read one byte at a time, but if you’re going to read plain text this is easier and produce more readable code.