import junit.framework.TestCase;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by y_str on 2017/11/9 0009.
*/
public class ObjectToFile extends TestCase {
public void test(){
List<Object> list = new ArrayList<Object>();
UserObj user = new UserObj();
user.setAge(20);
user.setUserId(1000L);
user.setUserName("测试");
list.add(user);
list.add(user);
try {
ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream("test.txt"));
ous.writeObject(user);
ous.writeObject(list);
ous.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
ObjectInputStream ins = new ObjectInputStream(new FileInputStream("test.txt"));
UserObj obj = (UserObj)ins.readObject();
List tempList = (List)ins.readObject();
System.out.println(obj.toString());
System.out.println(tempList.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class UserObj implements Serializable{
private Long userId;
private String userName;
private Integer age;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserObj{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
网友评论