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 Java to read file contents. We’ll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile:
Data: myfile.txt
1
2
3
4
5
6
7
8
We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:
The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.:
The equivalent Java code:
The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner’s position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files.
Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:

Note 8.3.1.

Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt.
Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code:
And the Java equivalent:
In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt.
You have attempted of activities on this page.