package Ser;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
Student s=new Student(1,"s");
Student s1=new Student(1,"s");
Student s2=new Student(1,"s");
list.add(s);
list.add(s1);list.add(s2);
Test t=new Test();
t.save(list);
for(Student st:t.input()){
System.out.println(st.name);
}
}
public void save(List<Student> list){
File file = new File(System.getProperty("user.dir") + ".dat");
try {
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream(file));
o.writeObject(list);
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public List<Student> input(){
File file = new File(System.getProperty("user.dir") + ".dat");
try {
ObjectInputStream o=new ObjectInputStream(new FileInputStream(file));
return (List<Student>)o.readObject();//这里有个警告类型安全:从 Object 强制类型转换为 List<Student> 实际上是对已擦除的类 型 List 进行检查 } catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return new ArrayList<Student>();
}
}
class Student implements Serializable{
private static final long serialVersionUID = 8;
//File f=new File(//);
int age;
String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(){}
public Student(int age,String name){
this.age=age;
this.name=name;
}
}