public class ObjectOuputStreamDemo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Write();
Read();
}
private static void Read() throws IOException, IOException, ClassNotFoundException {
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("d:\\12.txt"));
ArrayList<Person> ect = (ArrayList<Person>)oi.readObject();
for(Person arr: ect){
System.out.println(arr.getAge()+"***"+arr.getName());
}
oi.close();
}
//如果不用集合,会报异常,无法解决,只能try,catch
private static void Write() throws FileNotFoundException, IOException {
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("d:\\12.txt"));
Scanner sc=new Scanner(System.in);
ArrayList<Person>array=new ArrayList<Person>();
for(int i=1;i<=3;i++){
System.out.println("请输入第"+i+"个学生的姓名");
String name=sc.nextLine();
System.out.println("请输入第"+i+"个学生的年龄");
int age=Integer.parseInt(sc.nextLine());
Person p=new Person(name,age);
array.add(p);
}
os.writeObject(array);
//b=true;
os.close();
}
}
|