File I/O
[Framework practical 5 of 7]
This practical we're going to read some proper data into our application.
Here's a text file containing an image as values: in.txt. We're going to read this file in, store the data, and then write it out again. Make yourself a framework5 directory and save the file to it. We'll use the code from the lecture to read and write the file. If it helps, you can find a version of the lecture notes with the important code highlighted in purple text on the course outline page (right postit-style note on homepage). The code we'll use will be:
1) Code to make a FileReader.
2) Code to buffer a FileReader.
3) Code to read a file into a 1D String array.
4) Code to parse a 1D String array into a 2D double array.
5) Code to make a FileWriter.
6) Code to buffer a FileWriter.
7) Code to write a 2D double array as Strings.
The main thing is to try and understand the code as you go through the practical - so please ask questions if you're unsure about how things work.
First, let's make ourselves a new class for data reading and writing. Let's call it IO (remember, this needs to go in an IO.java file):
public class IO {
public double[][] readData() {
// Our reading code will go here.
return new double[][] {};
}
public void writeData(double[][] dataIn) {
// Our writing code will go here.
}
}
Note the return types and parameters. Note especially that we currently return an empty
2D double array from readData()
. This is to stop the compiler complaining we're not
returning anything here -- we'll replace it with the real return statement, returning the data we
read in, later.
Make this class now in the framework5 directory. In addition, copy the last version of your Analyst and Storage files in. Leave the Storage class as it is, but empty out the Analyst class so it looks like this:
public class Analyst {
public Analyst () {
Storage store = new Storage();
// Our Analyst code this practical will go here.
}
public static void main (String args[]) {
new Analyst();
}
}
Make sure you understand everything above, then we'll test the code.
What is the simplest thing we can test here? It is probably just to make
a IO object (called, say, io
) in our Analyst constructor and see if
it all compiles. Do that now and fix any problems.
Next, go on to Part Two, where we'll read in the data.