File I/O
[Framework practical 5 of 7]
Now we're going to write the data out.
First we need to get the data out of our storage 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 Analyst class to get the
data from the Storage class object store
and send it to this method inside IO.
This is the reverse of the process we saw in Analyst for the readData
method (again, you might like to use
store.data
if you don't have a store.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 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.
You might also want to see if you can mess around with the
data before you write it to the file, for example, using the rerangeArray
code. When you're
happy with your code, you're done.