packagecom.cmy.demo;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importcom.cmy.serial.Student;public classUserStudent {/***@paramargs
*@throwsIOException
*@throwsClassNotFoundException*/
public static void main(String[] args) throwsIOException, ClassNotFoundException {
Student st= new Student("Tom",'M',20,3.6);
File file= new File("C:\\YiKiChen\\pacho\\student.txt");try{
file.createNewFile();
}catch(Exception e) {
e.printStackTrace();
}//序列化 对象转换成io流
try{
FileOutputStream fos= newFileOutputStream(file);
ObjectOutputStream oos= newObjectOutputStream(fos);
oos.writeObject(st);
oos.flush();
oos.close();
fos.close();
}catch(Exception e) {
e.printStackTrace();
}//反序列 io转换成对象
try{
FileInputStream fis= newFileInputStream(file);
ObjectInputStream ois= newObjectInputStream(fis);
Student st1=(Student)ois.readObject();
System.out.println(st1.getName());
System.out.println(st1.getGpa());
System.out.println(st1.getSex());
}catch(FileNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/*** 对象转数组
*@paramobj
*@return
*/
public byte[] toByteArray (Object obj) {byte[] bytes = null;
ByteArrayOutputStream bos= newByteArrayOutputStream();try{
ObjectOutputStream oos= newObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes=bos.toByteArray ();
oos.close();
bos.close();
}catch(IOException ex) {
ex.printStackTrace();
}returnbytes;
}/*** 数组转对象
*@parambytes
*@return
*/
public Object toObject (byte[] bytes) {
Object obj= null;try{
ByteArrayInputStream bis= newByteArrayInputStream (bytes);
ObjectInputStream ois= newObjectInputStream (bis);
obj=ois.readObject();
ois.close();
bis.close();
}catch(IOException ex) {
ex.printStackTrace();
}catch(ClassNotFoundException ex) {
ex.printStackTrace();
}returnobj;
}
}