【问题标题】:Line Break in an ObjectOutputStream/ObjectInputStream in Java?Java 中的 ObjectOutputStream/ObjectInputStream 中的换行符?
【发布时间】:2014-04-19 14:45:30
【问题描述】:

我编写了一个简单的程序来将书籍、杂志等对象序列化和反序列化到一个文件中,并且我使用了 Java 实用程序库的 ObjectInputStream/ObjectOutputStream 类。

一切正常,但我想在每个对象后添加一些换行符,以便在打开文件时更具可读性。

在 ObjectInputStream/ObjectOutputStream 类中使用字符串时是否有“\n”的等效项?

PS:我还有一个版本,我使用 XStream 使用 xml 数据进行序列化和反序列化。有没有人有想法,如果也有可能,使用 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
            }
        }
    }

【问题讨论】:

    标签: java objectinputstream objectoutputstream


    【解决方案1】:

    您可以使用 write(int) 和 write(byte[]) 方法将任意数据注入 ObjectOutputStream。只要确保读取流的代码知道如何处理它。特别是换行符可以写成

    out.write('\n');
    

    也就是说,对象序列化格式并不是为人类可读而设计的。如果您想要人类可读的输出,我建议使用 JSON。

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 2012-05-29
      • 2016-04-11
      • 2017-09-06
      • 1970-01-01
      • 2011-07-18
      • 2023-01-25
      • 2019-06-07
      • 2011-10-26
      相关资源
      最近更新 更多