CS 117 Lab: Console and File Input/Ouput (I/O)

For this lab, we'll practice ways of getting information in and out of your Java programs, using both the console (terminal window) and files. You should not import javabook in any of these examples - we'll be doing pure, "official" Java. Create a project called FilePractice to use for all of the following examples.

Lab 0: Console output

This is something you already know how to do! Without any javabook code at all, write a Java program where you print "Hello world!" to the console window.

Lab 1: File output

0. Open up a terminal window by clicking on the icon that looks like a computer screen with a footprint on it.

1. Type pwd at the prompt. This will tell you the location of your home directory. (pwd = "print working directory")

2. Create a new class called FileTest. Remove the "import javabook.*" statement from the top.

3. Enter in the following Java program:

import java.io.*;

class FileTest
{
    public void fileWrite()
    {
        // You may need to change the location of your
        // output file if your home directory is in
        // a different location.
        PrintWriter out = new PrintWriter(new FileWriter
            ("/Accounts/cs/cs117s03/username/outputfile.txt"));

        out.print("Hello ");
        out.println("world");

        out.close();
    }
}

Then add a main method to FileTest:

public static void main(String[] args)
{
    FileTest fileTest = new FileTest();
    fileTest.fileWrite();
}

4. Try to compile the class FileTest. What goes wrong? This is because opening up a file could throw an IOException, which is a checked exception. This means you have to tell Java how to deal with it, or the program won't compile.

5. One method to fix it is to add a throws clause at the end of the method header, like this:

    public void fileWrite() throws IOException

Try adding "throws IOException" after your header (as above), and compile again.

Now try to compile FileTestMain. Why does the same problem happen again? fileWrite is allowed to throw an exception to main, but main does nothing with it. Add a "throws IOException" following the header to main in a similar fashion. Now try compiling.

6. Run your program. If all went successfully, open up NEdit (icon at the bottom like a window with an "N"), and File, then Open. Find outputfile.txt on the right hand size, and open it up. What do you see?

7. Try changing your directory name to something that doesn't exist, like /Accounts/nonsense. Run your program again. What happens? Your program should throw an exception indicating that the system cannot find a place to put the file outputfile.txt. This is because the folder nonsense does not exist. Fix this problem by changing the directory name back to what it should be.

8. Modify your program to write to the file five lines, each of which contains your name or a friend's name, followed by a space and then an age, then another space and then height in feet. For example:

Arlene 19 5.2
Bill 22 5.6
Marilyn 16 5.4
Bryan 35 5.7
Buzz 6 3.2

Lab 2: Console Input

Up until now, we have gotten input from a user by using SimpleInput. Now we'll do so using "built-in" console I/O.

0. Add the following method to your FileTest class:

         
public void consoleRead()
{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("What is  your first name? ");
    String first = in.readLine();
    System.out.print("What is  your last name? ");
    String last = in.readLine();
    System.out.println("Your name is " + last + ", " + first + ".");
}

1. Compile it. Add "throws" statements as necessary, or catch the exceptions and handle like we did in class.

2. Modify your main to run the consoleRead method, and recompile. Run your program. What does it do?

Lab 3: File Input

0. Add the following method to FileTest.
public void fileRead() throws IOException
{
    BufferedReader in = new BufferedReader(new FileReader
        ("/Accounts/cs/cs117s03/outputfile.txt"));
    String text = in.readLine();
    System.out.println(text);
    in.close();
}

1. Run the method. What do you see?  Modify this method to print out the names, ages, and height of the five people you stored back in Lab 1.

2. Add code to your program to try reading and printing three more people after you've read the five that are there. (Yes, this is a bad idea!) How does Java react?

3. A better way to read and print from a file is to use a while loop. Modify your code that prints the five people using code something like the following:

while (in.ready()) {
  text = in.readLine();
  System.out.println(text);
}

4. In reality, you would want to be able to separate each item on each line into different variables, rather than keeping all the information on name, age, and height in one string. To break it up, use a StringTokenizer. Here is an example of code that uses StringTokenizers. Play around with them, and see if you can adapt the same idea to have your program print out all five of your people, and then an average age and maximum height.

         
import java.util.*;
         
String text = "Beggars in Spain*Nancy Kress*1992*1.5";
StringTokenizer tokenizer = new StringTokenizer(text,"*");

String title = tokenizer.nextToken();
String author = tokenizer.nextToken();
String yearStr = tokenizer.nextToken();
String millionsSoldStr = tokenizer.nextToken();
int year = Integer.parseInt(yearStr);
double millionsSold = Double.parseDouble(millionsSoldStr);

Lab 4: Putting it All Together

The file /Accounts/courses/cs117/dmusican/web2.txt is a "dictionary" file containg a long list of words. Write a Java program to report the following information: