I want to write 3 object arrays to the same text file and load the data back to the arrays as well. However, I can only seem to get this to work with arr1
with the below code. How can I change this code to write the data of all 3 arrays to the same file and load the data back to their respective arrays?
import java.io.*;
public class CarCenter implements Serializable {
static CarCenter[] arr1 = new CarCenter[6];
static CarCenter[] arr2 = new CarCenter[6];
static CarCenter[] arr3 = new CarCenter[6];
public static void write() {
try {
FileOutputStream fos = new FileOutputStream("Data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arr1);
oos.writeObject(arr2);
oos.writeObject(arr3);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In your code you are only loading the value of arr1:
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
All you have to do is to read the other objects as well like this:
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
CarCenter[] saved2 = (CarCenter[]) ois.readObject();
arr2 = saved2;
CarCenter[] saved3 = (CarCenter[]) ois.readObject();
arr3 = saved3;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
Want to learn more?
I suggest reading the documentation itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.