今天实现一下如何从Object去转为byte和如何从byte转为Object。
首先,定义一个类student:
package com.byteToObject;
import java.io.Serializable;
public class student implements Serializable{
private int sid;
private String name;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后定义转换的主要方法,主要利用流进行转换:
package com.byteToObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
student stu = new student();
stu.setSid(123);
stu.setName("wanger");
ByteArrayOutputStream byam = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byam);
oos.writeObject(stu);
byte[] bytes = byam.toByteArray();
System.out.println(bytes.toString());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
student s = (student)ois.readObject();
System.out.println(s.getName());
}
}
转换结束