我正在尝试使用 DataOutputSteam 和 DataInputSteam 而不是 ObjectInputStream/ObjectOutputStream 来序列化/反序列化事物。
序列化失败。 txt 文件仍为空。 当然,test2字符串最终都是空的(无法反序列化空文件)。
这是我的对象:
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 !";
}
}
这是我的尝试:
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) {}
最佳答案
简单来说,调用dos.flush()
将强制系统获取缓冲的任何内容并将其实际写入磁盘。因此,您需要在尝试读取同一文件之前调用它。有关 flush()
的更多详细信息,我建议查看 What is the purpose of flush() in Java streams?因为之前已经回答过这个问题。
关于java - 如何使用DataOutputStream和DataInputStream进行序列化/反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314090/