Skip to main content

Java For Python Programmers Edition 2

Section 8.3 Reading Files

Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line’s content. In Java, you read files in a very similar way, however in Java we will use the Scanner class in order to iterate through the lines.
Consider the following Python code example that reads each line of the file and prints it to the console.
Data: myfile.txt
1
2
3
4
5
6
7
8
The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.
You may have noticed that there are some new methods you haven’t seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn’t. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.
You have attempted of activities on this page.