待序列化的类 实现Serializable接口
复制代码 代码如下:
package test.java;
import java.io.Serializable;
public class User implements Serializable{
private int id;
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;
}
private String name;
private int age;
}
测试类
复制代码 代码如下:
package test.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class MySerialization {
/**
* @param args
*/
public static void main(String[] args) {
String filePath="d:user.txt";
User user=new User();
user.setId(1);
user.setName("zhangsan");
user.setAge(22);
writeUser(user, filePath);
User user1=readUser(filePath);
System.out.println(user1.getId());
System.out.println(user1.getName());
System.out.println(user1.getAge());
}
public static void writeUser(Object object,String filePath){
ObjectOutputStream objectOutputStream=null;
try {
objectOutputStream=new ObjectOutputStream(new FileOutputStream(new File(filePath)));
objectOutputStream.writeObject(object);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static User readUser(String filePath){
ObjectInputStream objectInputStream=null;
User user=null;
try {
objectInputStream=new ObjectInputStream(new FileInputStream(new File(filePath)));
user=(User)objectInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return user;
}
}
输出结果
1
zhangsan
22