JavaIO之ObjectStream(一)

来源:互联网 发布:在线客服软件有哪些 编辑:程序博客网 时间:2024/05/21 22:45
package three.day.io;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class SerialiableObjectStream {
public static void main(String[] args){
try {
FileOutputStream fos = new FileOutputStream("ObjectStream.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 1; i <= 10; i++) {
Student stu = new Student(i, "李日中" + 1, 23+1 );
oos.writeObject(stu);
}
oos.close();
fos.close();
FileInputStream fin = new FileInputStream("ObjectStream.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
for (int i = 1; i <= 10 ; i++) {
System.out.println(ois.readObject());
}
ois.close();
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}


@SuppressWarnings("serial")
class Student implements Serializable{
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}
原创粉丝点击