java 中各种数据类型转换byte[]的方法

要求以下数据类型转换为byte[],并且从byte[]再转换回来,数据部丢失!shortintlongcharbooleanfloatdoubleStringClass

第1个回答  推荐于2017-11-26
ObjectOutputStream oos = null;//对象输出流
ByteArrayOutputStream baos = null;//byte数组输出流
ByteArrayInputStream bais = null;//对象输入流
try {
//序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);//将数组流传入对象流
oos.writeObject(new Integer(1));//用对象流读取对象。
byte[] bytes = baos.toByteArray();//用数组流将传入的对象转化为byte数组
//反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
Integer i = (Integer)ois.readObject();
System.out.println(i);
} catch (Exception e) {

}以上是把integer类型转化成byte[]数组类型。注:基本类型要转化为byte[]数组的话,需要用该基本类型的引用类。比如int的引用类是integer,就行了所有的类型,包括class都可以用这种序列化方式来转成byte[],本回答被网友采纳
第2个回答  2013-08-22
类型转换肯定有误差了.这个一般只用单方向的吧?
相似回答