NEW: For a prettier blog interface, see the Wordpress version!

At the end of this lesson, you will be able to read from and write to files.

If you practice at home, you will be able to add a Load/Save feature that saves and loads shapes from plain text files.

We will have a quiz today, so please listen carefully and ask lots of questions.

Objectives

At the end of this session, you should be able to:

Plan for learning

So we'll do writing first, then reading.

Structure of class

Brief lecture

Quiz

1/4 sheet of paper

Part 1:

Juan is a young boy who loves listening to his grandmother tell stories during family time. His grandmother speaks very slowly, though, and he has a hard time understanding her because sometimes she speaks one syllable or even one letter at a time. Fortunately, his older sister Maria patiently listens to their grandmother and then tells Juan each completed sentence.

What CS21B concept corresponds to:

Part 2:

Juan has a younger brother named Pedro who is beginning to learn how to write. Pedro can only write one letter at a time. Juan would like to help his brother practice writing, so when their parents tell them to write something down, Juan remembers what they're supposed to write down and he spells it out to Pedro one letter at a time. Pedro then writes each letter down on a large piece of paper. Their parents are happy because they don't have to spell things out themselves, but Pedro still gets to write the information down.

What CS21B concept corresponds to

Practice

Follow-up

By 11:59:59 PM on Monday, 2004.01.12, e-mail me an updated copy of your project code that allows you to load and save the shapes to plain text files named "circles.txt", "squares.txt", and "lines.txt" in the current directory.

We will have a closed-notes hands-on test on Tuesday, 2004.01.13.T he test will cover reading and writing from files and will last 45 minutes. Because of the short timeframe of the exam, you must practice until you can read from and write to files by writing code from scratch (without referring to your notes). You will not be given sample code then.

On Thursday, we'll talk about merging all three text files into just one, and also of storing each object's data on just one line.

Writing to a file

Sample code

// For the input and output
import java.io.*;

public class FileWriteTest
{
    public static void main(String[] args)
    {
        try
        {
            // Open the file
            FileWriter file = new FileWriter("song.txt");

            // Make it easy for us to print to that file
            PrintWriter output = new PrintWriter(file);

            output.print("On the first day of Christmas, my true love gave to me");
            output.println(" a partridge in a pear tree.");

            // Save and close the file
            output.close();
        }
        catch (IOException ex)
        {
            System.out.println("Error: " + ex);
            ex.printStackTrace();
        }
    }
}

Exercises

Do as many of these as you want until you feel comfortable with writing to files.

Reading from a file

Sample code

// For the input and output
import java.io.*;

public class FileReadOneLineTest
{
    public static void main(String[] args)
    {
        try
        {
            // Open the file
            FileReader file = new FileReader("song.txt");

            // Make it easy for us to read a line from that file
            BufferedReader input = new BufferedReader(file);

            String s = input.readLine();
            System.out.println(s);

            // Close the file
            input.close();
        }
        catch (IOException ex)
        {
            System.out.println("Error: " + ex);
            ex.printStackTrace();
        }
    }
}

Exercises

Do as many of these as you want until you feel comfortable with reading a number of lines from a file.

Reading all lines from a file

Sample code

// For the input and output
import java.io.*;

public class FileReadAllLinesTest
{
    public static void main(String[] args)
    {
        try
        {
            // Open the file
            FileReader file = new FileReader("song.txt");

            // Make it easy for us to read a line from that file
            BufferedReader input = new BufferedReader(file);

            // Read one line
            String s = input.readLine();

            // If readLine() ever returns null, we know we have reached
            // the end of the stream
            while (s != null)
            {
               // Process the current line
               System.out.println(s.toUpperCase());
               
               // Read the next line
               s = input.readLine();
            }

            // Close the file
            input.close();
        }
        catch (IOException ex)
        {
            System.out.println("Error: " + ex);
            ex.printStackTrace();
        }
    }
}

Exercises

Saving an object's data from a file

Sample code

// For the input and output
import java.io.*;

public class FileWriteDataTest
{
    public static void main(String[] args)
    {
        Person a = new Person("Sacha", "[email protected], +639195657116");
        Person b = new Person("God", "prayer");
        try
        {
            FileWriter file = new FileWriter("directory.txt");
            PrintWriter output = new PrintWriter(file);

            output.println(a.getName());
            output.println(a.getContactInfo());
            output.println(b.getName());
            output.println(b.getContactInfo());

            output.close();
        }
        catch (IOException ex)
        {
            System.out.println("Error: " + ex);
            ex.printStackTrace();
        }
    }
}

class Person
{
    private String name;
    private String contactInfo;

    public Person(String name, String contactInfo)
    {
        this.name = name;
        this.contactInfo = contactInfo;
    }

    public String getName()
    {
        return this.name;
    }

    public String getContactInfo()
    {
        return this.contactInfo;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setContactInfo(String name)
    {
        this.name = name;
    }
    
    public void greet()
    {
        System.out.println("Hello, " + this.name + "!");
    }
    
}

Exercises

public class CircleTest
{
    public static void main(String args[])
    {
        Circle a = new Circle(1, 2, 3);
        Circle b = new Circle(4, 5, 6);

        // Fill in the blanks here: save a, then b to a file called "circles.txt";
        // After you run this program, circles.txt should contain
        // 1
        // 2
        // 3
        // 4
        // 5
        // 6
    }
}

class Circle
{
    private int x;
    private int y;
    private int radius;

    public Circle(int x, int y, int radius)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public int getX() { return this.x; }
    public int getY() { return this.y; }
    public int getRadius() { return this.radius; }
    public double getArea() { return Math.PI * this.radius * this.radius; }
}

Reading one object's data from a file

Sample code

// For the input and output
import java.io.*;

public class FileReadOneRecordTest
{
    public static void main(String[] args)
    {
        Person p;
        try
        {
            FileReader file = new FileWriter("directory.txt");
            BufferedReader input = new BufferedReader(file);

            String name = input.readLine();
            String contactInfo = input.readLine();
            p = new Person(name, contactInfo);

            p.greet();

            output.close();
        }
        catch (IOException ex)
        {
            System.out.println("Error: " + ex);
            ex.printStackTrace();
        }
    }
}

class Person
{
    private String name;
    private String contactInfo;

    public Person(String name, String contactInfo)
    {
        this.name = name;
        this.contactInfo = contactInfo;
    }

    public String getName()
    {
        return this.name;
    }

    public String getContactInfo()
    {
        return this.contactInfo;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setContactInfo(String name)
    {
        this.name = name;
    }

    public void greet()
    {
        System.out.println("Hello, " + this.name + "!");
    }
    
}

Exercises

public class CircleTest
{
    public static void main(String args[])
    {
        // Read the first circle from "circles.txt"
        // by reading its x (convert to int)
        // and its y (convert to int)
        // and its radius (convert to int)
        // then creating the circle object with the specified values

        // then use the circle's getArea and print the area.
    }
}

class Circle
{
    private int x;
    private int y;
    private int radius;

    public Circle(int x, int y, int radius)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public int getX() { return this.x; }
    public int getY() { return this.y; }
    public int getRadius() { return this.radius; }
    public double getArea() { return Math.PI * this.radius * this.radius; }
}

Reading many objects' data from a file

Sample code

Exercises

public class CircleTest
{
    public static void main(String args[])
    {
        // open "circles.txt"
        // Do the following while there are still circles left:
           // Read each circle
           // by reading its x (convert to int)
           // and its y (convert to int)
           // and its radius (convert to int)
           // then creating the circle object with the specified values
           // then use the circle's getArea and print the area.
    }
}

class Circle
{
    private int x;
    private int y;
    private int radius;

    public Circle(int x, int y, int radius)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public int getX() { return this.x; }
    public int getY() { return this.y; }
    public int getRadius() { return this.radius; }
    public double getArea() { return Math.PI * this.radius * this.radius; }
}
Previous day | Next day

I'd love to hear about any questions, comments, suggestions or links that you might have. Your comments will not be posted on this website immediately, but will be e-mailed to me first. You can use this form to get in touch with me, or e-mail me at [email protected] .

Page: C S 21B.Streams
Updated: 2004-11-21
NOTE: ANTI-SPAM MEASURE NOW IN PLACE. Please answer the following question with the right number in order to send me your comment.
What is two minus one? (hint: one ;) )
Name:
E-mail:
URL:
Comments: