简体   繁体   English

如何使用DataOutputStream和DataInputStream进行序列化/反序列化?

[英]How to serialize/deserialize with DataOutputStream and DataInputStream?

I'm trying to serialize/deserialize things with DataOutputSteam and DataInputSteam instead of ObjectInputStream/ObjectOutputStream. 我正在尝试使用DataOutputSteam和DataInputSteam而不是ObjectInputStream / ObjectOutputStream进行序列化/反序列化。

The serialization fails. 序列化失败。 The txt file remains empty. txt文件保持为空。 Of course, the test2 strings are all empty in the end (can't deserialized an empty file). 当然,test2字符串最后都是空的(不能反序列化一个空文件)。

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) {}

For a short explanation, calling dos.flush() will force the system to take anything buffered and actually write it to disk. 为了简短说明,调用dos.flush()将强制系统采取任何缓冲内容,并将其实际写入磁盘。 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? 有关flush()更多详细信息,我建议查看Java流中flush()的目的是什么? as this has been answered before. 正如之前已经回答过的

Try closing the output file before you open it for reading. 打开输出进行读取之前,请尝试关闭输出文件 On some systems eg Windows you won't succeed in the second open. 在某些系统(例如Windows)上,第二次打开不会成功。

Closing it will flush the BufferedOutputStream. 关闭它会刷新BufferedOutputStream.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM