Activity 4.2 - Reading from a text file

Topic

In this activity, we read lines from a sample text file and print them out one by one.

Materials

In addition to the Solution document, the project for this activity contains two classes:

In addition there is a text file sample1.txt which is not part of the project but which can be found in the project folder.

Task

The run method of the class Read_a_File is to read successive lines of the file sample1.txt and print them out one by one, halting when there are no more lines.

Instructions

Do not run the project at this stage, it will not yet compile.

The Scanner class you were introduced to in Activity 4.1 can be employed to read from any input stream, not just System.in.

To read from a file, we use the filename to construct a File object, then create a Scanner for the File object, like this:

Scanner sc = new Scanner(new File(filename));

Once the Scanner is created we can read lines from it using nextLine() just as we did in Activity 4.1.

Open the class Read_a_File and complete the code where indicated.

Run the project to read an instructive quote from a computing pioneer.