【问题标题】:Java serializable object to byte array to file has garbage at the beginning of the fileJava 可序列化对象到字节数组到文件在文件开头有垃圾
【发布时间】:2015-09-28 18:23:59
【问题描述】:

我可以通过以下方式将可序列化的 Java 对象保存到文件中:

Object mySerializableObj;

// assign value to mySerializableObj

try 
{
    writer = new BufferedWriter(new FileWriter(strFile1ToWritePath));
    writer.write(part.toString());
    return error;
} 
catch (Exception ex)
{}

但是,我需要将该对象作为字节数组发送。但是,当我尝试这样做时:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try 
{
    out = new ObjectOutputStream(bos);   
    out.writeObject(mySerializableObj);
    byte[] objBytes = bos.toByteArray();
    FileOutputStream fos2 = new FileOutputStream(strFile2ToWritePath);
    fos2.write(objBytes);
    fos2.close(); 
} 
catch (Exception ex){}

如果我比较两个结果文件,我会得到一些二进制垃圾。否则它们是相同的。

前置的二进制是 AC ED 00 05 7C 00 00 00 00 00 13 34 FB 我可以从http://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html 的 JavaWorld 文章“Java 序列化算法揭示”中看到 这是“按设计运行”。

有没有办法避免这种情况?

谢谢, 伯特

【问题讨论】:

  • 为什么?你打算如何反序列化没有流头的字节数组?
  • “需要将该对象作为字节数组发送”是什么意思?您将它作为字节数组发送,只是以特定的编码。文件是字节序列。 ObjectOutputStream 执行序列化魔法,这听起来像是你不想要的。

标签: java serialization bytearray


【解决方案1】:

尝试覆盖writeStreamHeader()ObjectOutputStream

喜欢

 public class MyObjectOutputStream extends ObjectOutputStream {
      public MyObjectOutputStream (OutputStream out) throws IOException {
         super(out);
      }
      @Override
      protected void writeStreamHeader() throws IOException {

      }
 }

【讨论】:

  • 然后呢?你有一个无用的数据。
猜你喜欢
  • 2011-02-19
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
相关资源
最近更新 更多