University of Washington, CSE 142

Lab 6: File Processing

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Basic lab instructions

Today's lab

Goals for today:

[an error occurred while processing this directive]

Files

So far, we've used Scanners to read user input. Now, we're going to look at using Scanners to read over files!

A File object allows you to interact with actual files on your computer. Make sure to put any file you want to read with a Scanner in the same folder as the program that wants to use it!

    // necessary to use Files
    import java.io.*;

    // makes a File object, holding the same info as the file named "actualNameOfFile"
    File fileVariableName = new File("actualNameOfFile");

    // a Scanner that reads over the File!
    Scanner fileScanner = new Scanner(fileVariableName);
Method name Parameters Description
exists() a String file name returns true if a file w/ the given file name exists in the same folder.
[an error occurred while processing this directive]

Scanner methods

Method name Description
next() reads and returns the next token as a String
nextLine() reads and returns as a String all the characters up to the next new line (\n)
nextInt() reads and returns the next token as an int, if possible
nextDouble() reads and returns the next token as double, if possible
hasNext() returns true if there is still a token in the Scanner
hasNextLine() returns true if there is still at least one line left to be read in the Scanner
hasNextInt() returns true if the next token can be read as an int
hasNextDouble() returns true if the next token can be read as an double

Recap: Scanner method examples

Suppose we have a Scanner trying to read over the following:
    4.2 abc 4
The following methods would read this as:
Method What happened? What's going on?
nextInt() java.util.InputMismatchException tried to read next token 4.2, couldn't process it as an int.
nextDouble() returns 4.2 as a double. tried to read next token, succeeded because it could be read as a double.
next() returned "4.2" as a String. read the next word as a String.
nextLine() returns "4.2 abc 4" as a String. read the whole next line as a String.
[an error occurred while processing this directive] [an error occurred while processing this directive]

New methods: Scanner method examples

Suppose we have a Scanner trying to read over the following:
    4.2 abc 4
The following methods would read this as:
Method Returned Why?
hasNextInt() false the next token is a double, and thus cannot be read as an integer.
hasNextDouble() true the next token is a double!
hasNext() true the next token can be read as a String!
hasNextLine() true there exists a line of input!

Exercise : .hasNext() caution

.hasNext() methods only check the type of the next token. .next() methods consume tokens, changing what token the Scanner is looking at next! For each of the following, enter the output if the loop terminates, or write infinite if the loop loops forever!

Consider the following as part of input.txt

Jello world :)
Scanner input = new Scanner(new File("input.txt"));
while (input.hasNext()) {
   String nextWord = input.next();
   System.out.print(nextWord + " ");
}
Jello world :) 
Scanner input = new Scanner(new File("input.txt"));
while (input.hasNext()) {
   System.out.println("hi");
}
infinite

[an error occurred while processing this directive]

File Exceptions

When you work with Files, the Java compiler gets concerned that you might be trying to access a File that doesn't exist. So any method that uses Files must declare that it might throw a FileNotFoundException: this basically tells Java that if the desired "actualNameOfFile" cannot be found, it's okay to crash.

Every method that directly or indirectly calls a method that works with Files also needs to declare that it might throw a FileNotFoundException.

  public static void main(String[] args) throws FileNotFoundException {
                           ...
  }
[an error occurred while processing this directive]

.next() vs .nextLine()

String Scanners

Consider the following problem:

Read over an input File, print out the # of times the word "the" shows up on each line.

We already know how to read full lines or individual words from a Scanner. Now we need a new strategy: we need to read lines from the input, and then we need to somehow read word-by-word through each line.

We can do this by creating a second Scanner! So far, we've used Scanners to read user input and to read Files. Scanners can also read over Strings!

    Scanner fileScannerName = new Scanner(new File("fileName"))
    while (fileScannerName.hasNextLine()) {
       String line = fileScannerName.nextLine(); // reads the next line from the input file
       Scanner lineScanner = new Scanner(line);
       while (lineScanner.hasNext()) {
          String word = lineScanner.next(); // reads the next word from the input line
          ...
       }
    }
[an error occurred while processing this directive]

Checkpoint: Congratulations!

Nice job making it this far--labs are tough! Feel free to work with the person next to you for the remaining slides. Labs are a unique opportunity (unlike homework) to collaborate directly on ideas, and practice peer programming.

These next problems get a little more challenging as we explore earlier concepts further.

We put a lot of problems in here so that you have plenty to refer back to later when working on homework. Don't feel bad if you don't finish all of them--Brett can't finish them all in a 50 minute lab, either! :)

Forest the cat says good job!

[an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive]

If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!