本文展示了如何在Java中把一个对象转换为byte[] 或字节数组,反之亦然。
1.将一个对象转换为byte[]
下面的例子显示了如何使用ByteArrayOutputStream 和ObjectOutputStream 将一个对象转换为byte[] :
// Convert object to byte[]
public static byte[] convertObjectToBytes(Object obj) {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
ois.writeObject(obj);
return boas.toByteArray();
} catch (IOException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
// Convert object to byte[]
public static byte[] convertObjectToBytes2(Object obj) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
ois.writeObject(obj);
return boas.toByteArray();
}
}
2.将byte[]转换为对象
下面的例子展示了如何使用ByteArrayInputStream 和ObjectInputStream 将byte[] 转换回一个对象:
// Convert byte[] to object
public static Object convertBytesToObject(byte[] bytes) {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
// Convert byte[] to object
public static Object convertBytesToObject2(byte[] bytes)
throws IOException, ClassNotFoundException {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
}
}
// Convert byte[] to object with filter
public static Object convertBytesToObjectWithFilter(byte[] bytes, ObjectInputFilter filter) {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
// add filter before readObject
ois.setObjectInputFilter(filter);
return ois.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
进一步阅读
下载源代码
$ git clonegithub.com/mkyong/core…
$ cd java-io/com/mkyong/io/object