Welcome to Lesson 21!


Learning Objectives
By the end of today's class, you should know...
  • How do you use loops to read from and write to a file in your program?
  • Final exam review

Announcements

  • Lab 10 due Friday
  • Final exam Tuesday, December 11 from 9:15-11:15am in this classroom
    • Final must be taken on this date at this time. No makeup finals, no exceptions!
    • If you need accommodations, please book them today!
    • How to study: 
      • Final Exam Prep
      • Midterms
      • Midterm Review Guides
      • Review Activities form Each Lesson
      • Final will be cumulative from first day of class through today's lesson
      • Will draw heavily from the final exam prep
      • Will give you one of two programs on final exam prep
      • Will also select one method from your Methodical worksheets, and one method two Arrays and Methods worksheets
  • Today, will spend the first part of class on File I/O
  • Second part of class will be final review
  • Office hours are over - no more late work will be accepted!
  • De Anza Library is open until 11 pm on the following dates.
    Dec 5th, from 8 am to 11 pm
    Dec 6th, from 8 am to 11 pm
    Dec 10th, from 8 am to 11 pm
    Dec 11th, from 8 am to 11 pm


Review Activity

With a partner, answer the following questions:

  • Assume you have a text file named infile.txt that contains the following data: 13.5 19.0 12.4
  • Write four lines of code to do the following:
    1. Create a new File object to connect to infile.txt
    2. Create a new Scanner object to read from the file
    3. Read the first number from the file and store it as a double variable named num1.
    4. Close the Scanner.
  • Assume you have a text file named outfile.txt
  • Write four lines of code to do the following:
  1. Create a new File object to connect to outfile.txt
  2. Create a new PrintWriter object to write to the file
  3. Write the message "Hello World!" to the file
  4. Close the PrintWriter.

File I/O Continued

Using Loops to Read Files

  • Sometimes you do not know how many lines are in a file
  • To solve this, the typical approach is to use a loop to process the file
  • The Scanner object has methods like hasNext() to see if there is any more input in the stream
  • You can use these methods to signal when your program reaches the end of a file

Example Program Testing for End-of-File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import java.io.*;
import java.util.Scanner;

public class Files {
public static void main(String[] args)
throws IOException {
File data = new File("sonnet.txt");
Scanner input = new Scanner(data);

while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
}

}

Some Test Methods of a Scanner Object

Method Description
hasNext() Returns true if this scanner has another token in its input.
hasNextLine() Returns true if there is another line in the input of this scanner.
hasNextDouble() Returns true if the next token can be interpreted as a double value.
hasNextInt() Returns true if the next token can be interpreted as an int value.

Activity 21.1: Averages (10pts)

  • We are going to write a program that takes in a list of numbers of unknown size from a file, and then outputs the average of these numbers.
  • This activity will help you practice using a loop to help you read data from a file.
  • Open up a new Java project and name it Averages
  • Now add the two import statements that are required for file I/O to the top of your program:
import java.util.Scanner;
import java.io.*;

  • Next, lets create a new File variable at the top of main and pass it in the name of the file "nums.txt"
File infile = new File("nums.txt");
  • Then, let's Scanner to open this file.
Scanner input = new Scanner(infile);

  • Next, lets read in the numbers from the file. Since we are computing the average of the numbers, we need two pieces of information
1. The sum of the numbers
2. How many numbers there are
  • Remember: Average = sum / count
  • Therefore, as we read in the numbers from the file, we need to computer their sum and count how many there are.
  • We will therefore need two variables to keep track of this information. Add the following two variable declarations to the top of main:
double sum = 0.0;
int count = 0;
  • We will also need a variable to temporarily store each number as we read it in from the file. Add an additional variable declaration to the top of main like so:
double num;
  • Now, let's read in the numbers from the file and process them inside a loop. Add the following loop to your program:
while (input.hasNextInt()) {
    num = input.nextInt();
    System.out.println("Processing the number: " + num);
    sum += num; //adding the number to our running total for the sum
    count++; //counting how many numbers are in the file
}
  • Now, let's print the average to the console and output it to a file.
  • To print the average to the console, add the following line of code:
System.out.println("The average is: " + sum/count);
  • To output the average to a file, we need to open a new output file. Below the print statement, add the following line of code:
File outfile = new File("average.txt");
  • Then, we need to connect this file to an output stream.
PrintWriter output = new PrintWriter(outfile);
  • Finally, lets write the average to the file.
output.println("The average is: " + sum/count);
  • As a last step we need to close our input and output streams. Add the following lines of code to the bottom of main:
input.close();
output.close();
  • Let's create a file to test our program. Open up a new empty file in Eclipse and name file nums.txt. In the file, add a list of numbers like this:
10 20 30 40 50
  • Now, run the code and open up your file to make sure everything is working properly. Open up the file averages.txt and verify that you got the correct output.
  • When you are finished, upload Averages.java to Canvas.

Activity 21.2: Sonnet Statistics (10 pts)

  • Open up a new Java project named Statistics and add the starter code below to it:
import java.io.*;
import java.util.Scanner;

public class Statistics {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{

        int count = 0;

        String word, line;

        //rest of code goes here

    }

}

  • Now, using Eclipse, create a new empty file called sonnet.txt and copy and paste the below sonnet into your file:

Shall I compare thee to a summer’s day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,
And summer’s lease hath all too short a date;
Sometime too hot the eye of heaven shines,
And often is his gold complexion dimm'd;
And every fair from fair sometime declines,
By chance or nature’s changing course untrimm'd;
But thy eternal summer shall not fade,
Nor lose possession of that fair thou ow’st;
Nor shall death brag thou wander’st in his shade,
When in eternal lines to time thou grow’st:
So long as men can breathe or eyes can see,
So long lives this, and this gives life to thee.

  • We are going to write some code to count the number of words and the number of lines in this file.
  • Declare two new files at the top of your program:

File infile = new File("sonnet.txt");

File outfile = new File("statistics.txt");


  • Also declare a new Scanner and connect it to infile.
  • Now, let's write a while loop to count up how many words are in the file.
while (input.hasNext()) {
    word = input.next();
    count++;
}
  • Finally, declare a new PrintWriter, connect it to outfile and print out the number of words contained in the file
    output.println("The sonnet has " + count + " words");
  • Now, close your input file stream.
    input.close();

  • Now, we need to count the number of lines in the file.
  • For this purpose, we are going to need a new input file stream as we already used the previous one to count the number of words in the file (and we cannot reset the input stream to point to the beginning of the file).
  • Add the following code to your program below the statement to close fin:
    input = new Scanner(infile);

  • Next, we are going to write a while loop to count the number of lines in the file.
count = 0; //reset count variable to 0
while (?????) {
    //what goes here?
    count++;
}
  • Write an print statement to print out the number of lines in the sonnet.
The sonnet has 14 lines.
  • Finally, close input and output and run your program.
  • Note that you should get 114 words and 14 lines.
  • Did you get the expected result inside of statistics.txt?
  • Submit your code to Canvas when you are finished.

Group Activity
  • Find a partner. 
  • Copy and paste this document into a new Word or Google Doc.
  • With your partner, answer the questions.
  • Answer key posted tonight.
~Good Luck Studying!~