0

我想检查中的字节是ostream表示序列化对象还是字节数组:

ByteArrayOutputStream ostream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(ostream);
out.writeObject(new TestClass());
out.flush();
out.close();

byte[] bytes = ostream.toByteArray();
isSerializedObject(new ObjectInputStream(
  new ByteArrayInputStream(bytes)))); // returns false
isSerializedObject(new ByteArrayInputStream(bytes))); // returns true

的代码isSerializedObject如下所示:

public static boolean isSerializedObject(InputStream istream) throws Exception {
  int size = 2;
  PushbackInputStream pis = new PushbackInputStream(istream, size);
  byte[] buffer = new byte[size];
  pis.read(buffer);
  // serialized data can be identified by the following two bytes
  boolean flag = buffer[0] == 0xAC && buffer[1] == 0xED;
  pis.unread(buffer);
  return flag;
}

有人可以解释为什么我使用 an时isSerializedObject返回但使用 a 时返回吗?falseObjectInputStreamtrueByteArrayInputStream

4

1 回答 1

0

为什么?只需 (a) 使用 writeObject() 而不是 write() 写入字节数组,然后 (b) 读取对象并在之后使用“instanceof”。容易得多,而且它不涉及窥探协议。

于 2013-01-31T23:35:49.307 回答