Lecture 14 (Sherriff) - Files

Lecture Date: Friday, February 13

Up to this point, you have been getting all of your input for your programs from the user from the keyboard. This is great, but what if you wanted to read in hundreds, or even thousands, of data points to run your program against. To say it would get tedious is probably an understatement.

For the next few lectures, we’ll learn how to read files as input instead of just the keyboard.

First, though, we’ll make our own very simple data set. Create a new file in a project called classmates.csv. In that file, put the names of the five or six people sitting around you.

Then try out this code:

Classmates.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.File;
import java.util.Scanner;

public class Classmates {

  public static void main(String[] args) throws Exception {
      Scanner inputFile = new Scanner(new File("classmates.csv"));
      while(inputFile.hasNextLine()) {
          String line = inputFile.nextLine();
          System.out.println(line);
      }

  }

}

Reading a file is as easy as reading from the keyboard… in fact, we use many of the same methods in Scanner!

Note the major difference though: we use .hasNextLine() in a while loop to check to see if there is another line in the file we need to read. As long as there is, then the while loop will keep executing until we’ve read all the lines.

We’ll do some more examples with some other data files!

Let’s try reading a file from the Internet. How is that different? (Ans: We use URL instead of File)

https://cs1110.cs.virginia.edu/temp.txt

Here are some data sets you should download so we can use them either in this class or later ones:

And here’s some example code: