CSCI 235 Lab 18: 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 16. 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 16 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/lab18
cd lab18

Take a look at how this differs from what you saw in lab 16. 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.

Note that one instance variable—the grid the sprite inhabits—doesn’t get included in the file.

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. The simplest way is to use RGB encoding: class Color has a constructor that takes a single int, and there is an instance method getRGB() that gives you the single-integer version of a color you already have.

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 plus the grid it is to inhabit.

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 lab18 with the command

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