Java Tutorial #3 Reading files with BufferedReader and printing out line numbers
Previous tutorial https://steemit.com/java/@nicetea/java-tutorial-2-writing-to-a-file-with-fileoutputstream
This time, I will paste the code directly and explain it below. Do you guys think that this kind of style is better? Drop a comment below, please!
Create a file "steemit.txt" with the following contents:
Java
and
Steemit
tutorials
The code:
public static void main(String[] args) {
BufferedReader f;
String line;
int z = 1;
try {
f = new BufferedReader(new FileReader("steemit.txt"));
while ((line = f.readLine()) != null) {
System.out.println(z + ": " + line);
z++;
}
f.close();
} catch (IOException e) {
System.out.println("Error while reading");
}
}
So again, we are starting with the main method, but this time we are using a try{} catch{} statement to catch potential errors. Next, we are declaring variables which will be used in the heart of the progam.
Inside the try{ we are assigning a new BufferedReader to the object f.
This time, we are reading the file line by line and not by byte. If the line is null (not existent / empty), the program will quit.
Inside the while we are printing out the current line number by the help of the variable z and the actual contents of the line. After the while loop has finished, we have to close the file.
Lastly, we add the error handling code, which will be executed if any error occured.