Search code examples
javaserializationdeserializationdatainputstreamdataoutputstream

How to serialize/deserialize with DataOutputStream and DataInputStream?


I'm trying to serialize/deserialize things with DataOutputSteam and DataInputSteam instead of ObjectInputStream/ObjectOutputStream.

The serialization fails. The txt file remains empty. Of course, the test2 strings are all empty in the end (can't deserialized an empty file).

Here is my object :

public class Test implements Serializable {
    public String[] nom;


    public Test() {

        nom = new String[5];
        nom[0] = "Coucou";
        nom[1] = "Je suis un tab de String";
        nom[2] = "Je vais me faire serialiser";
        nom[3] = "Et deserialiser aussi !";
        nom[4] = "Je suis le roi du monde !";
    } 
}

Here is my try :

    Test test = new Test();
    Test test2 = new Test();


    test2.nom[0] = "";
    test2.nom[1] = "";
    test2.nom[2] = "";
    test2.nom[3] = "";
    test2.nom[4] = "";

     DataInputStream dis;
     DataOutputStream dos;

   // serialisation manuelle
    try {
      dos = new DataOutputStream(
              new BufferedOutputStream(
                new FileOutputStream(
                  new File("nom2.txt"))));

      for(int i = 0; i < 5; i++)
      {  
             dos.writeUTF(test.nom[i]);
      } 
        } catch (FileNotFoundException e) {
    } catch (IOException e) {}      




    // deserialisation manuelle
       dis = new DataInputStream(
              new BufferedInputStream(
                new FileInputStream(
                  new File("nom2.txt"))));

    try { 
        test.nom[0] = dis.readUTF();
        test.nom[1] = dis.readUTF();
        test.nom[2] = dis.readUTF();
        test.nom[3] = dis.readUTF();
        test.nom[4] = dis.readUTF();
            } catch (FileNotFoundException e) {
    } catch (IOException e) {}

Solution

  • For a short explanation, calling dos.flush() will force the system to take anything buffered and actually write it to disk. For this reason, you need to call it before you try reading from the same file. For more details on flush(), I recommend looking at What is the purpose of flush() in Java streams? as this has been answered before.