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:
- modify sample file code to perform a specified task
- learn more about file handling from the documentation
- list the classes and methods you used
Plan for learning
- Checking if you've written a file correctly: Easy, just open in a text editor.
- Checking if you've read from a file correctly: Hard, unless you've tested the rest of your code
So we'll do writing first, then reading.
Structure of class
Brief lecture
- What are streams?
- What are files?
- How do we work with streams and files in Java?
- What resources can we use to learn more?
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:
- 1. one of the stories of Juan's grandmother
- 2. Juan's grandmother when she's telling the story
- 3. Maria
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
- (same as 1) the piece of paper Pedro writes on
- 4. Juan when he's helping Pedro by remembering and spelling things out
- 5. Pedro
Practice
- Simple exercises for reading and writing files
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.
- Write a program that prints your favorite poem to a file called "poem.txt" in the current directory.
- Write a program that prints the lyrics of the 12 days of Christmas to "12days.txt". Use a loop so that you don't actually have to write a gazillion print statements.
- Write a program that reads a line from the user (remember JOptionPane.showInputDialog?) to a text file called "chat.txt". The program should not overwrite the text file each time you call it, but only add it to the end. Hint: search on the Internet or check out the JDK documentation for FileWriter.
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.
- Find out what happens when you try to read a file that does not exist.
- Find out what happens when you try to read more lines from a file than it actually has.
- If you don't have a file called "poem.txt" yet, use Notepad to create it. Make sure it has at least three lines. Write a program that displays the first three lines of "poem.txt".
- If you don't have a file called "poem.txt" yet, use Notepad to create it. Make sure it has at least three lines. Write a program that displays the first three lines of "poem.txt" in reverse order - the third line, then the second line, then the first.
- Write a program that prints out the first line of a file in reverse
- that is, abcd should become dcba.
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
- Print out all the lines in "song.txt" as is.
- Print out all the lines in "song.txt", but convert them to small.
- Print out all the lines in "song.txt", but in reverse order. The last line should be printed first, and so on.
- Print out every other line of "song.txt".
- Given several filenames as arguments to your Java program (remember the args[] array?), print out all of their contents.
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", "sacha@sachachua.com, +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; }
}
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 sacha@sachachua.com .