如何使BufferedInputStream可序列化?

时间:2019-05-22 05:52:58

标签: java

我需要使Java BufferedInputStream可序列化。是否有其他选择或其他实现方式?

在此实施过程中,您看到任何问题了吗

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.Serializable;

public class SerializableBufferedInputStream extends BufferedInputStream implements Serializable
{
  public SerializableBufferedInputStream(InputStream in)
  {
    super(in);
  }

  public SerializableBufferedInputStream(InputStream in, int size)
  {
    super(in, size);
  }
}

1 个答案:

答案 0 :(得分:0)

首先,BufferedInputStream创建一个BufferedInputStream并保存其参数(输入流)供以后使用。 但是您说的是Serializable,这意味着将对象的状态转换为字节流 那么为什么需要转换它?

这件事可能会帮助您检查(如果您不想要,请提供您的代码)

public class MainClass {

public static void main(String[] args) throws Exception {
    Punk obj1 = new Punk("A");
    Punk obj2 = new Punk("B");
    Punk obj3 = new Punk("V");
    ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(
            new FileOutputStream("C:/punkObjects.bin")));

    objectOut.writeObject(obj1); // Write object
    objectOut.writeObject(obj2); // Write object
    objectOut.writeObject(obj3); // Write object
    objectOut.close(); // Close the output stream

    ObjectInputStream objectIn = null;
    int objectCount = 0;
    punk object = null;

    objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream(
            "C:/punkObjects.bin")));

    // Read from the stream until we hit the end
    while (objectCount < 3) {
        object = (punk) objectIn.readObject();
        objectCount++;
        System.out.println(object);
    }

    objectIn.close();

}
}

class Punk implements Serializable {

String str;

public Punk(String s) {
    str = s;
}
}