Welcome to Lesson 20!


Learning Objectives
By the end of today's class, you should know...
  • More about using arrays in method
  • What is a stream?
  • How do you use the Scanner class to read data from a file into your program?
  • How do you use the PrintWriter class to write data from your program into a file?

Announcements

  • Lab 10 due Friday
  • Last homework of the quarter assigned for tonight!
  • Last office hour of the quarter is this Thursday at 8:30am
    • No late work accepted after this office hour
    • No late work accepted that is more than one week late
    • Last office hour is likely to be packed - please arrive early or you may not get helped
  • Final exam one week from today
    • 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 prepare:
    • Final will be cumulative
    • Study over Midterm 1 and Midterm 2
    • Final exam review released on Thursday covering material since last midterm


Review Activity

  • Declare an array of Strings called pets and assign it the values dog, cat, rabbit, bird in TWO DIFFERENT WAYS (static and non-static initialization)
  • Print out the contents of the above array using a for loop, with each element on its own line.
  • Now, write a method called printArray:
    • The method takes in an array of Strings as a parameter
    • It prints out each element in the String array on its own line
    • It returns nothing

Activity 20.1: Arrays and Methods Worksheet (10 pts)

  • Find a partner for pair programming
  • Copy the following into a new file called ArrayMethods.java.
  • Write the methods one-by-one. Compile and run your code after you write each method to make sure it was written properly.
  • When your code passes all of the tests, upload your file to Canvas.
  • Both partners need to submit for full credit.
public class ArrayMethods {

    /**
     * prints the contents of an array to the console using a for loop
     * @param data the array to print
     */
    public static void printArray(int[] data) {
        return;
    }

    
    /**
    * Given an array of ints, return true if 10 appears as
    * either the first or last element in the array. The array will be size 1 or more.
    * first10Last([1, 2, 10]) → true
    * first10Last([10, 1, 2, 3]) → true
    * first10Last([13, 10, 1, 2, 3]) → false
    * @param data the array of integer values
    * @return whether or not 10 appears as the first or last element
    */
    public static boolean first10Last(int data[]) {
        return false;
    }
    
    /**
    * Given an array of ints, return true if the array is size 1 or more,
    * AND the first element and the last element are equal.
    * equalFirstLast([1, 2, 3]) → false
    * equalFirstLast([1, 2, 3, 1]) → true
    * equalFirstLast([1, 2, 1]) → true
    * @param array the array of integers
    * @return whether the first and last element are identical
    */
    public static boolean equalFirstLast(int[] array){
        return false;
    }
    
    /**
    * Given an array of ints, add 2 to each element in the array
    * return nothing.
    * arrayPlus2([1,2,3]) -> [3, 4, 5]
    * arrayPlus2([10, 30, 50, 79, 85]) -> [12, 32, 52, 81, 87]
    * arrayPlus2([5]) -> [7]
    * @param array the array of integer values
    */
    public static void arrayPlus2(int array[]) {
        return;
    }
    
    /**
     * Given an array of ints, multiplies each element in the array by itself
     * squareArray([1,2,3]) -> [1, 4, 9]
     * squareArray([3, 5, 6, 8, 9]) -> [9, 25, 36, 64, 81]
     * squareArray([5]) -> [25]
     * @param array the array of integer values
     */
    public static void squareArray(int[] array){
        return;
    }
    

    public static void main(String[] args)
    {
      
        boolean answer;
      
        System.out.println("***Testing first10Last***\n");
        int array1[] = {1, 2, 10};
        answer = first10Last(array1);
        System.out.println("Should print true: " + answer);
        int array2[] = {10, 1, 2, 3};
        answer = first10Last(array2);
        System.out.println("Should print true: " + answer);
        int array3[] = {13, 10, 1, 2, 3};
        answer = first10Last(array3);
        System.out.println("Should print false: " + answer);
        System.out.println();

        System.out.println("***Testing equalFirstLast***\n");
        int array4[] = {1, 2, 3};
        answer = equalFirstLast(array4);
        System.out.println("Should print false: " + answer);
        int array5[] = {10, 20, 50, 60, 80, 90, 10};
        answer = equalFirstLast(array5);
        System.out.println("Should print true: " + answer);
        int array6[] = {1};
        answer = equalFirstLast(array6);
        System.out.println("Should print true: " + answer);
        System.out.println();

        System.out.println("***Testing arrayPlus2***\n");
        int array7[] = {1, 2, 3};
        arrayPlus2(array7);
        System.out.println("Should print 3 4 5: ");
        printArray(array7);
        System.out.println();
        int array8[] = {10, 30, 50, 79, 85};
        arrayPlus2(array8);
        System.out.println("Should print 12 32 52 81 87: ");
        printArray(array8);
        System.out.println();
        int array9[] = {5};
        arrayPlus2(array9);
        System.out.println("Should print 7: ");
        printArray(array9);
        System.out.println("\n");

        System.out.println("***squareArray***\n");
        int array10[] = {1, 2, 3};
        squareArray(array10);
        System.out.println("Should print 1 4 9: ");
        printArray(array10);
        System.out.println();
        int array11[] = {3, 5, 6, 8, 9};
        squareArray(array11);
        System.out.println("Should print 9 25 36 64 81: ");
        printArray(array11);
        System.out.println();
        int array12[] = {5};
        squareArray(array12);
        System.out.println("Should print 25: ");
        printArray(array12);
        System.out.println("\n");

        System.out.println("***End of Tests***");
       


    }

}

File I/O

About Program I/O

  • Program I/O = Program Input/Output
    • Input to and output from programs
  • Input can be from a keyboard, mouse or file
  • Output can be to a display screen, printer or file
  • Note that files can be both input and output devices for programs
  • Advantages of file I/O:
    • Data still exists after the program ends
    • Input can be automated (rather than entered manually)
    • Output from one program can be input to another
  • To store and retrieve data in a file, we need two items:
    • A file
    • A file stream object
  • We will look at files first

Files

File: a collection of data stored under a common name on a storage medium.

  • Files provide long-term storage of large amounts of data
  • Usually, you store files on non-volatile storage mediums
    • Magnetic disks
    • Optical disks
    • Flash storage, like USB storage devices
  • File are a single sequence of bytes

    Byte 0 Byte 1 Byte 2 ... Byte n−1 End-of-file marker

  • The operating system keeps track of the number of bytes in a file
  • Files must have a name
    • Naming requirements depend on the underlying operating system (OS)
  • The operating system organizes files into directories


Types of Files

  • All data in a file is ultimately just zeros and ones
  • It is up to the program using the file to understand the meaning and internal format of the data
  • In general, programs interpret data using two broad categories: text and binary

Text Files

  • In text files, the bits represent printable characters
  • Files are usually stored as one byte per character (ASCII)
  • Each line is delimited by end-of-line character
  • You can read text files because each byte is interpreted by a program as textual characters
  • Some of these programs, like NotePad, then display the textual data to your computer's screen
  • Since there are many programs that read and display text, text files are called human readable

Binary Files

  • Data other than text is usually referred to as binary data
  • Each bit represents some type of encoded information like program instructions or integer data
  • Binary files are easily read by the computer but not by humans
  • The following table compares binary and text values saved in a file
  • First we consider the value "1234" as Unicodes and compare these bits to a binary value of 1234


Comparing Binary and Textual Data

Description Byte 0 Byte 1 Byte 2 Byte 3
"1234" as char's '1' '2' '3' '4'
"1234" as ASCII codes (bytes) 49 50 51 52
"1234" as ASCII codes (bits) 00110001 00110010 00110011 00110100
(int) 1234 as binary bits 00000000 00000000 00000100 11010010


Creating File Objects

  • File class represents a file on the native file system
  • You create a File object referring to a file
  • Then you can query the object for information about that file

Common Constructors for Class File

Class Description
File(String pathname) Creates a File object that refers to the specified pathname.
File(String parent, String child) Creates a File object that refers to the pathname created by combining the parent and child pathnames.
File(File parent, String child) Creates a File object that refers to the pathname created by combining the pathname of parent with the child pathname.

Examples of Creating Files Objects

  • You can create a File object in the current directory:
    File myFile = new File("myfile.txt");
  • Can create a File object using an absolute pathname
  • Specifies the entire path and file name for the file:
    File myFile = new File("C:/docs/myfile.txt");

Using File Objects

  • We can use File objects for many tasks
  • For instance we can:
    • Test some attributes of files or directories
    • Get information about files
    • Get lists of directory contents
    • Create files and directories
    • Delete files and directories
  • You can see some of the commonly used methods listed below

Some Methods that Test a File

Method Description
canRead() Returns true if the pathname exists and can be read by the program.
canWrite() Returns true if the pathname exists and a program can write to it.
exists() Returns true if the pathname exists.
isDirectory() Returns true if the pathname exists and refers to a directory.
isFile() Returns true if the pathname exists and refers to a file.

Other Methods that work with File Objects

Method Description
createNewFile() Creates a new, empty file if a file with this name does not yet exist.
delete() Deletes the file or directory referred to by the File object.
setReadOnly() Makes the file read-only. If successful, returns true.

Working with Files and Directories

  • The following programs show some uses for the File object

Getting Information About a File

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

public class FileInfo {
  public static void main(String[] args) throws IOException {
    File myFile = new File("myfile.txt");
    myFile.createNewFile();
    if (myFile.exists()) {
        System.out.println("Name:     " + myFile.getName());
        System.out.println("Path:     " + myFile.getPath());
        System.out.println("Writable: " + myFile.canWrite());
    } else
        System.out.println("The " + myFile.getName()
                + " file doesn't exist.");
  }
}

Streams

Stream: a one-way transmission path that either delivers data to a destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)

  • A stream connects a program to an I/O object
  • Input stream: an object that provides a sequence of bytes to a program

  • Output stream: an object that accepts a sequence of bytes from a program

File Streams

File stream: a one-way transmission path used to connect a program to a file.

  • File streams can be either input or output streams
  • File input streams receive data from a file
  • File output streams send data to a file
  • Each file your program uses will need a separate file stream object

Text Streams

  • Streams are implemented using classes and objects - a topic you will cover in more detail next quarter
  • To write and read text, you use character streams
  • A character stream processes characters through the stream
  • There is a separate set of classes for writing and reading character streams. In this class, we will be using:
    • PrintWriter: Connects a stream to a file for writing data from the program to the file
    • Scanner: Connects a stream to a file for reading data from a file into the program

Connecting a Character Input Stream to a File
  • To "read" from a text file, you need to create a character input stream
  • We can use the same Scanner object we used for reading from the keyboard
  • An example of how to accomplish this task is shown below

Example Connecting a Character Input Stream to a File

import java.io.*;
import java.util.Scanner;
public class Files {
public static void main(String[] args) throws IOException{

File file = new File("scores.txt");
Scanner input = new Scanner(file);
int score = input.nextInt();
System.out.println("Score " + score);
input.close();
}
}

Some Commonly Used Methods of a Scanner Object

Method Description
next() Returns the next token as a String object.
nextLine() Returns the rest of the current line as a String object.
nextDouble() Provides classes to handle text, dates, and numbers
nextInt() Returns the next token as an int value.


Procedure For Reading a Text File
  1. Place import java.io.*; at the top of your program
    1. Note that .* is the wildcard. Using a * will import all classes from that package.
  2. Add throws IOException as part of the signature for main to avoid compiler errors.
  3. Create a File object with a pathname to your file:
    File data = new File("data.txt");
    
  4. Add a Scanner object to parse the data in the file:
    Scanner input = new Scanner(data);
    
  5. Read data using methods calls for the correct type:
    int x = input.nextInt();
    
  6. Close the streams when finished reading:
    in.close();
    

Note that you can nest the constructor calls as shown in the example below

Example Program Reading a Text File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

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

class TextReaderApp {
    public static void main(String[] args)
            throws IOException {
        File data = new File("data.txt");
        Scanner input = new Scanner(data);
        String str = input.nextLine();
        System.out.println(str);

        char ch = input.nextLine().charAt(0);
        System.out.println(ch);

        int x = input.nextInt();
        System.out.println(x);

        double d = input.nextDouble();
        System.out.println(d);

        for (int i = 0; i <= 10; i++) {
            x = input.nextInt();
            System.out.print(x + " ");
        }
        System.out.println();

        input.close();
    }
}

Writing to a Text Stream

  • To "write" text to a file, we use a PrintWriter stream:
    PrintWriter output = new PrintWriter("out.txt"); 

Example program to write out data to a file:

import java.io.*;
public class Files {
    public static void main(String[] args) throws IOException{
    
        File file = new File("scores.txt");
        PrintWriter output = new PrintWriter(file);
       
        output.print("100, 95, 90, 85");
        output.close();  
    }
}

Procedure for Writing a Text File
  1. Place import java.io.*; at the top of your program
    1. Note that .* is the wildcard. Using a * will import all classes from that package.
    2. We need 3 classes here so we will save time by using the * instead of importing all 3 separately (java.io.File, java.io.PrintWriter, and java.io.IOException)
  2. Add throws IOException as part of the signature for main to avoid compiler errors.
  3. Create a File object with a pathname to your file:
    File data = new File("data.txt");
    
  4. Connect the file to a stream:
    PrintWriter out = new PrintWriter(data);
    

    If you want to append data then use:

    PrintWriter out = new PrintWriter(data, true);
    
  5. Write to the file using the print() and println() methods:
    out.println("This is a string");
    out.println('c');
    out.println(1234);
    out.println(1.234);
    for (int i = 0; i <= 10; i++) {
        out.print(i + ",");
    }
    out.println();
    
  6. Close the streams when finished writing:
    out.close();
    

Example Program Writing a Text File

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

import java.io.*;

class TextWriterApp {
    public static void main(String[] args)
            throws IOException {
        File data = new File("data.txt");
        PrintWriter out = new PrintWriter(data);
        out.println("This is a string");
        out.println('c');
        out.println(1234);
        out.println(1.234);
        for (int i = 0; i <= 10; i++) {
            out.print(i + " ");
        }
        out.println();
        out.close();
        System.out.println("Finished writing file");
    }
}


Activity 20.2: Two Numbers (10 pts)

  • In this exercise we write a program that copies two numbers from an input stream to an output stream.
  • Create a new Java project and name it Files.
  • Then, let's create a text file to test our program.
  • In Eclipse, click on the name of the project. Then, go to File->New->File
  • Name this file infile.txt.
  • In the file, add a list of numbers each on their own line, like this:
10
20

  • We will read from this file after writing our program.

  • Next, create a second file named outfile.txt. You can leave this file blank.
  • We will write out to this file in our program.
  • Place the following import statement above main:
    import java.io.*; 
  • Also, as part of the signature of main(), add throws IOException:
    public static void main(String[] args) throws IOException{
    
  • Add code to create two new Files:
    File inFile = new File("infile.txt");
File outFile = new File ("outfile.txt"); 
  • Add statements to read two numbers from the input stream. For example, here is possible code for reading the first number:
    Scanner input = new Scanner(inFile);
    int first = input.nextInt();
    
  • Add statements to write the two numbers to the output stream. For example, here is possible code for writing the first number:
    PrintWriter output = new PrintWriter(outFile); 
  • output.println("first=" + first);
    
  • Close the streams when finished reading and writing:
    input.close();
    output.close();
    
  • Compile and run your modified program to make sure you made the changes correctly.

    Notice that you do not see any output on the screen for file reading or writing. The output stream wrote the program output to the output file.

  •  Now, open the output file you created and verify that two numbers were copied. Your output file should look like:
    first=10
    second=20
    
  • Save your program source code file to submit to Canvas

Your Files.java File Should Look Similar to the One Below:




Wrap Up
  • With a partner, answer the questions from today's learning objectives


Upcoming Assignments


~See You Thursday!~