一个student的对象,将其转为字节流数组以及相反的过程。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
class Student{//simple class
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ByteAndObjectText {
public static Student ByteToObject(byte[] b) throws IOException{
ByteArrayInputStream bais=new ByteArrayInputStream(b);
DataInputStream dis=new DataInputStream(bais);
Student stu=new Student();
// for(int i=0;i<size;i++){
stu.setName(dis.readUTF());
stu.setAge(dis.readInt());
//}
return stu;
}
public static byte[] ObjectToByte(Student stu) throws IOException{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
dos.writeUTF(stu.getName());
dos.writeInt(stu.getAge());
return baos.toByteArray();//转换为字节流。
}
public static void main(String[] agrs) throws IOException{
Student stu1=new Student("wfj",20);
Student stu2=ByteAndObjectText.ByteToObject(ByteAndObjectText.ObjectToByte(stu1));
System.out.println("the stu2 same as stu1: "+stu2.getName()+" "+stu2.getAge());
}
}