[英]Line Break in an ObjectOutputStream/ObjectInputStream in Java?
I've written a simple program to serialize and deserialize objects like books, magazines and so on into a file, and I've used the ObjectInputStream/ObjectOutputStream classes of the Java utility library. 我编写了一个简单的程序来将对象(例如书籍,杂志等)序列化和反序列化为文件,并且使用了Java实用程序库的ObjectInputStream / ObjectOutputStream类。
Everything works, but I would like to add some line breaks after every object, so that it is more readable when opening the file. 一切正常,但是我想在每个对象之后添加一些换行符,以便在打开文件时更具可读性。
Is there any aquivalent for the "\\n" when using Strings in the ObjectInputStream/ObjectOutputStream classes? 在ObjectInputStream / ObjectOutputStream类中使用字符串时,“ \\ n”是否等效?
PS: I've also a version where i serialize and deserialize with XStream using xml data. PS:我还有一个版本,其中我使用xml数据使用XStream进行序列化和反序列化。 Has anyone an idea, if there exists also a possibility, to make such a break using XStream? 有没有人知道使用XStream进行这样的中断(如果存在的话)?
OutputStream fos = null;
ObjectOutputStream o = null;
// Now serialize objects into the file
try
{
fos = new FileOutputStream("C:\\Users...");
// Initialize the ObjectOutputStream with XStream when xml_switcher is set to true
if (xml_switcher == true) {
o = xstream.createObjectOutputStream(fos);
}
// Otherwise normal serializing by creating a normal ObjectOutputStream
else {
o = new ObjectOutputStream( fos );
}
ArrayList<Printing> resultList = Access.getAllPrintings();
Iterator<Printing> it = resultList.iterator();
while (it.hasNext()) {
if (xml_switcher == true) {
o.writeObject(it.next());
// So here's my problem: I would like to have something like o.write("\n")
// using XStream
}
else {
o.writeObject(it.next().toString());
// Same here but without XStream
}
}
}
You can inject arbitrary data into an ObjectOutputStream using the write(int) and write(byte[]) methods. 您可以使用write(int)和write(byte [])方法将任意数据注入ObjectOutputStream中。 Just make sure that the code reading the stream knows how to handle it. 只要确保读取流的代码知道如何处理它即可。 A line break in particular can be written with 特别是换行符可以写成
out.write('\n');
That said, the object serialization format is not designed to be human readable. 就是说,对象序列化格式并非旨在人类可读。 If you want human readable output I suggest using JSON. 如果您想要人类可读的输出,建议您使用JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.