1、测试类
package com.wyq.print;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestObjectOutputStream {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
/**
* 写入
*/
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\a.txt"));
oos.writeObject(new String("JLFDSJSLKDJFALKSD"));
oos.writeInt(12);
oos.writeBoolean(false);
// oos.close();
Person per =new Person("李四",18);
System.out.println(per);
oos.writeObject(per);
oos.writeObject(new Person("张三", 12));
oos.write('a');
oos.flush();
/**
* 读取
*/
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://a.txt"));
System.out.println(ois.readObject());
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.read());
Person p = (Person) ois.readObject();
System.out.println(p.getName()+"\t"+p.getAge());
ois.close();
}
}
2、自己编写类
package com.wyq.print;
import java.io.Serializable;
public class Person implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
}
3、总结:
1)自己编写的类一定要实现Serializable接口,否则不能往文件中写入数据
2)读取与写入的类型应该先相同,这种情况下更少出错