As stated by others, if you want to write binary, don't use the toString()
method when serializing the object. You also need to implement Serializable
in class myClass
. Then deserializing is just as simple as serializing, by using ObjectInputStream.readObject()
.
Your resulting SaveData
class should then look something like this:
import java.io.*;
import java.util.*;
public class SaveData {
int counter = 1;
public void saveTheData(ArrayList<myClass> myClassObj) {
try {
FileOutputStream fout = new FileOutputStream(counter
+ "SaveGame.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(myClassObj);
counter++;
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<myClass> loadTheData(int saveNum) {
try {
FileInputStream fin = new FileInputStream(saveNum + "SaveGame.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
ArrayList<myClass> myClassObj = (ArrayList<myClass>) ois.readObject();
ois.close();
return myClassObj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
And myClass
would look something like this:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class myClass implements Serializable {
private static final long serialVersionUID = /* some UID */;
/* ...
* class properties
*/
myClass(/* args */) {
// Initialize
}
/* ...
* class methods
*/
private void writeObject(ObjectOutputStream o) throws IOException {
// Write out to the stream
}
private void readObject(ObjectInputStream o) throws IOException,
ClassNotFoundException {
// Read in and validate from the stream
}
}