如何使用PushbackInputStream检查字节数组?

时间:2013-01-31 21:36:44

标签: java io

我想检查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;
}

有人可以解释为什么isSerializedObject在我使用false时会返回ObjectInputStream但在我使用true时会返回ByteArrayInputStream吗?

1 个答案:

答案 0 :(得分:0)

为什么呢?只需(a)使用writeObject()而不是write()编写字节数组,然后(b)读取对象并在之后使用“instanceof”。更简单,它不涉及偷看协议。