Answer the question
In order to leave comments, you need to log in
How to write a class to a file in java?
There is a project with a genetic algorithm optimization, where each result must be written to a file. It is written to the file, but it is written like this: <header><data><header><data> ... <header><data>, which causes the error java.io.StreamCorruptedException: invalid type code: AC when reading the file , so I need the file to be written as <header><data><data>...<data>. I don't know how to do it correctly, so here's the code:
String fileName = "data.bin";
try {
FileOutputStream fileOs = new FileOutputStream(fileName,true);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
os.writeObject(m);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIs = new FileInputStream(fileName);
final ObjectInputStream is = new ObjectInputStream(fileIs);
List<Model> models = new ArrayList<>();
int counted = 0;
while(true) {
try {
Model model = (Model) is.readObject();
counted++;
models.add(model);
System.out.println("i="+counted+", model = "+model.toString()+"; fithess = "+m.fitness);
} catch (EOFException e) {
is.close();
fileIs.close();
break;
} catch (ClassNotFoundException e) {
e.printStackTrace();
is.close();
fileIs.close();
break;
}
}
System.out.println("Counted "+counted);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Answer the question
In order to leave comments, you need to log in
Isn't it easier to write in JSON?
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question