![](/img/trans.png)
[英]Java object serialization, how to use same file after using it with ObjectOutPutStream
[英]Java: How to add static text to file using ObjectOutputStream
我正在 Java 中开发一个小型应用程序。 At certain point i need to save the object of my custom class to a text file for this i override toString()
method in my custom class and then use ObjectOutputStream
class to save object of my custom class to text file. 现在一切正常,即文本文件包含预期的文本。 以下三行包含主要代码
ObjectOutputStream outputStream = null;
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(person);//person is the instance of my custom class
现在,我如何将一些 static 数据与 object 数据一起添加到我的文件中
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.WhatFunctoinToUse("some static text");//What function i use to add static text??
outputStream.writeObject(person);//person is the instance of my custom class
简短的回答:你没有。
ObjectOutputStream
并不意味着以这种方式使用。 它以 API 指定的格式输出一个Serializable
object。 这并不总是一个好主意,即在未来的版本中很容易破坏兼容性。
虽然输出的格式看起来可读,但它包含许多不可打印的字符,添加一些 static 文本可能会破坏序列化。
您正在寻找的是:
a) 明文序列化如 JSON 或 XML (试试http://simple.sourceforge.net/ ,很简单)
b) 除了序列化的 object 之外的文本文件。
你不应该尝试扩展ObjectOutputStream
的功能,除非你有一个非常好的理由,而且你似乎没有。
If you want to append a primitive type value to be flattened with an Object, pass your ObjectOutputStream
to PrintStream
to enable you append a new line which will effect hold the static
value as require.
阅读和写作见下文。
//Writting
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("person.out"));
outputStream.writeObject(person);
PrintStream pst = new PrintStream(outputStream);
pst.append("Some static Value");
outputStream.flush();
outputStream.close();
pst.close();
// Reading
ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.out"));
Perrson person=(Person) in.readObject();
String staticText =in.readLine();
in.close();
希望您意识到,通过使用 ObjectOutputStream 并向其写入person
,您实际上是在序列化person
object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.