public class Test {
public static void main(String[] args) throws IOException {
File file = new File("cat.txt");
//ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream
ObjectOutputStream obOutput = null;
//ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化
ObjectInputStream obInput = null;
Cat c3 = null;
obOutput = new ObjectOutputStream(new FileOutputStream(file));
obInput = new ObjectInputStream(new FileInputStream(file));
Vector<Cat> ve = new Vector<Cat>();
for(int i=0;i<5;i++){
Cat c= new Cat("cat"+i,i*10);
ve.add(c);
}
try {
//writeObject 方法用于将对象写入流中
for(int i=0;i<ve.size();i++){
obOutput.writeObject((Cat)ve.get(i));
}
//刷新该流的缓冲。此操作将写入所有已缓冲的输出字节,并将它们刷新到底层流中
obOutput.flush();
obOutput.close();
for(int i=0;i<ve.size();i++){
//readObject 方法用于从流读取对象
c3 = (Cat)obInput.readObject();
if(c3.year>20){
System.out.println("大猫"+c3.name+"----"+c3.year);
}else{
System.out.println(c3.name+"----"+c3.year);
}
}
obInput.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Cat implements Serializable{//在对象流中存储或恢复的所有类需实现Serializable
private static final long serialVersionUID = 1L;
String name;
int year;
public Cat(String name, int year) {
super();
this.name = name;
this.year = year;
}
}
对象流
最新推荐文章于 2021-06-28 09:42:35 发布