Lab 17: File I/O

The goal of this lab is to practice file I/O, handling exceptions, and writing action listeners.

1. Introduction

In this lab we will revisit the Sprite program from lab 15. This time we will give the program the facility to save the current state of the simulation and reload it later.

The program should work as before but with two changes:

For your convenience, the GUI and File I/O handouts from class are available online.

I have provided solutions for the lab 15 functionality, with a little bit of rearrangement. There are two features of Sprites.java that you should notice:

2. Set up

Follow these set-up instructions carefully.

Make a directory for this lab and cd into it. First, copy files from the course directory for this lab:

hg clone /cslab/class/csci235/labs/lab17
cd lab17

Take a look at how this differs from what you saw in lab 15. I have provided the action listeners and dialogs, but you will need to fill in some methods.

Remember that you will need to include -cp simulation.jar:. with both the javac and java commands.

3. Designing a file format

First, discuss with your partner how you can save/store a collection of Sprites. You'll need to decide on a file format, which will need to include a way to format each of the Sprites. At the end of this week's Sprite.java, you'll find a place to describe your format in a comment.

The trickiest part of this will be figuring out how to write out the Color value in a way that it can be re-constructed. One path to that is to look at the constructors for Color; you want to find a constructor for which there is a corresponding method returning the value. (Try to keep it simple. And you can rule out anything having to do with "system properties".)

You can uncomment or replace the final section in Sprite.java. You'll need something like what is there to encapsulate the conversion. The suggestion is to have format() produce a single string, and to have a constructor that can make a Sprite from one of those strings.

4. Writing the SaveListener

Next, finish the saveSprites() method in the SaveListener class. Most of this will involve calling the writeSprites() method in class Sprites. Note that you need to catch any exceptions; you can display a message back to the user using the provided label.

A lot of the work is going to be in class Sprites, where you need to iterate over all of the sprites to write them to a file.

5. Loading a saved configuration

Finally, in the file Sprites.java, find the portion of code that will load a configuration from a file and fill-in what's missing.

6. Turn in

Turn in your source files as lab17 with the command

/cslab/class/csci235/bin/handin lab17 *.java

Thomas VanDrunen, Cary Gray
Last modified: Thu Apr 23 08:22:22 CDT 2015