gpt4 book ai didi

java - 如何使 BufferedInputStream 可序列化?

转载 作者:行者123 更新时间:2023-12-02 05:22:33 26 4
gpt4 key购买 nike

我需要使 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);
}
}

最佳答案

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

这个东西可以帮助你检查(如果你想要其他的,请提供你的代码)

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

关于java - 如何使 BufferedInputStream 可序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com