File I/O for Assignment 5
Tl;dr: [FileIO.zip]
You learnt in lecture that you can read/write different types of files, including Text files and Binary files. You should study both for the final, and can read about File I/O in chapter 10 of your textbook.
For Assignment 5, I recommend writing to a Text file.
There are two parts to File I/O in A5:
- Saving simulations (2 marks)
You have to be able to save the user-specified settings, plus current environment values at each sample increment. - Viewing saved simulations (2 marks)
You should be able to load the user-specified settings, plus current environment values, from a previously saved simulation.
First of all, Java uses streams to handle any input/output. A stream is a sequence of bytes, and you need to convert these bytes into something you can process (characters).
Example
Echo is a program which takes a text file line by line, printing out each line to the console. Several things are happening here:
- If you run the program with an argument, you can include a file name. eg. java Echo "sampleFile.text" will result in "sampleFile.text" being in args[0].
- Create a FileReader, passing in the file name as a parameter to the constructor. FileReader reads the bytes in the file.
- Create a BufferedReader, passing in the FileReader as a parameter to the constructor. BufferedReader turns the bytes into characters (datatype is char, recall that Strings are arrays of characters).
- Use the readLine() method on the BufferedReader to get a line of text from the file. Print it out using System.out.println()
- Repeat this process until there are no lines, and readLine() returns null.
import java.io.*;
public class Echo{
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
String line = in.readLine();
while (line != null){
System.out.println(line);
line = in.readLine();
}
in.close();
}
}
Assignment 5
Write a line of numbers to file, then read the first line to load the initial values of your scenario.
Let's say I entered all the values, and started a simulation. The very first state I save to file should be the starting values of my scenario. If I want to load a scenario, I should load this first line to restore my initial values.
With my simulation running, the program should continue to store each state of the program (each update) to the file, to create a log.
I have written some code to demonstrate this process [FileIO.zip]. You will have to get all the numbers from your UI, but the writing/reading is the same.