序列化与反序列化的区别
序列化 是JAVA对象转字节流反序列化 是字节流转JAVA对象
JavaBean
public class User implements Serializable {
private int id;
private String name;
private int age;
public User ( int id, String name, int age) {
super ( ) ;
this . id = id;
this . name = name;
this . age = age;
}
public User ( ) {
super ( ) ;
}
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
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 demo {
public static void main ( String[ ] args) {
ObjectOutputStream oos= null;
try {
oos= new ObjectOutputStream ( new FileOutputStream ( "C:/Users/user/Desktop/aabbcc.txt" ) ) ;
User user = new User ( 1 , "liqian" , 23 ) ;
oos. writeObject ( user) ;
oos. flush ( ) ;
} catch ( Exception e) {
} finally {
try {
if ( oos!= null) {
oos. close ( ) ;
}
} catch ( Exception e2) {
}
}
}
}
反序列化
public class demo {
public static void main ( String[ ] args) {
ObjectInputStream ois= null;
try {
ois= new ObjectInputStream ( new FileInputStream ( "C:/Users/user/Desktop/aabbcc.txt" ) ) ;
User user = ( User) ois. readObject ( ) ;
System. out. println ( "用户ID:" + user. getId ( ) + " 用户姓名:" + user. getName ( ) + " 年龄:" + user. getAge ( ) ) ;
} catch ( Exception e) {
} finally {
try {
if ( ois!= null) {
ois. close ( ) ;
}
} catch ( Exception e2) {
}
}
}
}