Instead of using a text file to save all the point coordinates one by one, change the savaData method and the constructor of the Model class to use object serialization and a binary file called "points.bin" to write / read the whole arraylist of points to / from the file in one operation. Use the Test class to run all the tests for the software and check that all the tests still work. Use the Start class to run the software and check that closing the software correctly saves the arraylist of points in the file "points.bin" (you can find the file in the folder for your current project but it is a binary file so you will not be able to read its content). Run the software again and check that all the points from the previous run are correctly displayed.
时间: 2023-07-02 19:05:45 浏览: 126
To implement this, we need to use Java's object serialization feature. Here are the steps to modify the `Model` class:
1. Make the `Point` class implement the `Serializable` interface.
```
public class Point implements Serializable {
// existing code
}
```
2. Modify the `Model` class constructor to read the `points.bin` file and deserialize the `ArrayList` of points from it:
```
public Model() {
try {
FileInputStream fileIn = new FileInputStream("points.bin");
ObjectInputStream in = new ObjectInputStream(fileIn);
points = (ArrayList<Point>) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
points = new ArrayList<>();
}
}
```
3. Modify the `saveData` method to serialize the `ArrayList` of points and write it to the `points.bin` file:
```
public void saveData() {
try {
FileOutputStream fileOut = new FileOutputStream("points.bin");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(points);
out.close();
fileOut.close();
} catch (IOException e) {
System.out.println("Error saving data to file.");
}
}
```
With these changes, the `Model` class will now read/write the entire `ArrayList` of points in one operation using object serialization.
To test that everything works, we can modify the `Test` class to use the new `Model` constructor and the `Start` class to use the new `saveData` method.
Here's an example implementation of the `Test` class:
```
public class Test {
public static void main(String[] args) {
Model model = new Model(); // use new constructor
// existing tests
// ...
model.saveData(); // save data after tests
}
}
```
And here's an example implementation of the `Start` class:
```
public class Start {
public static void main(String[] args) {
Model model = new Model(); // use new constructor
// existing code to display points
// ...
model.saveData(); // save data on exit
}
}
```
With these changes, the software will now use object serialization to read/write the entire `ArrayList` of points from/to the `points.bin` file. Running the `Test` class should still pass all the tests, and running the `Start` class should correctly display all the points from the previous run.
阅读全文