我正在尝试使用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) {}
答案 0 :(得分:1)
对于简短的解释,调用dos.flush()
将强制系统采取任何缓冲并实际将其写入磁盘。因此,您需要在尝试从同一文件中读取之前调用它。有关flush()
的详细信息,建议您查看What is the purpose of flush() in Java streams?,因为之前已经回答过。
答案 1 :(得分:0)
在打开输出文件进行阅读之前,请尝试关闭输出文件。在一些系统,例如Windows在第二次打开时没有成功。
关闭它将刷新var text = document.createTextNode("Hello world"),
break = document.createElement("br"),
section = document.getElementById("section");
section.appendChild(text);
section.appendChild(section);