这两种写法上都没有错,
ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream(fiel)));
BufferedInputStream oos=new BufferedInputStream (new ObjectInputStream(new FileInputStream(file)));
只要记得用ObjectOutputStream写入对象,就一定要用ObjectInputStream读取
不过第二种这么写好像没有什么意义啊
你看这段代码
- <P>class Person implements Serializable{
- private String name;
- private int age;
- Person(String name,int age){
- this.name=name;
- this.age=age;
- }
- public String toString(){
- return name+"*****"+age;
- }
- }
- public class Demo {
- public static void main(String[] args)throws Exception{
- // writeObject();
- readeObject();
- }
- public static void readeObject()throws Exception{</P>
- <P> </P>
- <P>//这是你写的第一种写法,就是在原来的基础上加了个缓冲
- ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream("a.txt")));
- // ObjectInputStream ois=new ObjectInputStream(new FileInputStream("a.txt"));
- Person p=(Person)ois.readObject();
- sop(p);
- ois.close();
- }
- public static void writeObject()throws IOException{</P>
- <P> </P>
- <P>//这是你写的第二个把ObjectOutputStream加入缓冲,这里你就无法将一个对象序列化了,所以说这么写没有什么意义</P>
- <P>//这么写是没错的,只要是OutputStream或其子类就可以
- BufferedOutputStream oos=new BufferedOutputStream(new ObjectOutputStream(new FileOutputStream("a.txt")));
- // ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("a.txt"));
- oos.writeObject(new Person("lisi",25));</P>
- <P>oos.close();
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }</P>
复制代码
|