File I/O
[Agent practical 6 of 9]


Now we're going to write the data out.

If we do this after our agents have run, we'll be writing out the results of our model on the environment.


First we need to get the data out of our Environment class and into a writeData method in the IO class. If you haven't already, write the following method declaration into the IO class.

   public void writeData(double[][] dataIn) {
      // Our writing code will go here.
   }

Then add the appropriate code to the Model class to get the data from the Environment class object world and send it to this method inside IO. Put this in the constructor after any code to run the model has finished.

This code is the reverse of the process we saw in Model for the readData method (again, youll need a world.getData()).


Next we need to write the data out to a file. Again, let's hardwire the file in for the moment:

   public void writeData(double[][] dataIn) {
      File f = new File("out.txt");
   }


Next, use your notes from the lecture to write the file writing code into the writeData method.

Don't start by trying to do everything. Start by trying to write a single word to the file, rather than the array. If you run code to do this, and change it, running it again, the code will simply write a new file over the old one, this isn't a problem.

Then add in code to loop through the array. You'll then need to convert each figure in the array into a String before you write it out. In total the code will look something like this:

   public void writeData(double[][] dataIn) {
      File f = new File("out.txt");

      // Code to make a FileWriter (again, in a try-catch block).
      // Code to wrap it in a BufferedWriter.

      // Open a try block.
         // Start of loops.
            // Code to change the double to a String.
            // Write the String to the file.
         // End loops
         // Close Buffer (and thus the FileWriter as well)
      // Close try block.

   }


Once you've got that done, test it works and you're done. You should now be able to run your model with some real environmental data in it!

How do we test it? Well, if we tested that readData() worked from the Model class, thus:

world.setData(io.readData());

what would the reverse code look like (we want to get io to write data we get from world)?


This practical we've mainly concentrated on Input and Output. In the next practical we'll start to build up a windows framework for our model, tying some of this functionality to menus etc.

You might like to replace the hardwired file locations with FileDialogs, one with its constructor's mode set to FileDialog.LOAD and the other FileDialog.SAVE. Again, the code is in the lecture slides; you'll need to import java.awt.* to use FileDialogs.