J
J
John Ashley2016-06-11 18:38:33
Java
John Ashley, 2016-06-11 18:38:33

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();
        }

What the code does: creates a data.bin file, writes the result of the algorithm execution (Model class) to it, then saves and closes the output stream. It then tries to read every result in that file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abs0lut, 2016-06-12
@abs0lut

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 question

Ask a Question

731 491 924 answers to any question