开发者社区> 问答> 正文

Java中从文件中读取ArrayList报错 ?报错

java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)

代码
import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Data {
private File file=new File("e:"+File.separator+"message.txt");
private ObjectInputStream ois;
private ObjectOutputStream oos;
public ArrayList read() throws FileNotFoundException, IOException{
ArrayList list=new ArrayList();
ois=new ObjectInputStream(new FileInputStream(file));

    try {



        list=(ArrayList<Message>) ois.readObject();//报错的位置


        ois.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}
public void write(ArrayList<Message> list){
    try {
        oos=new ObjectOutputStream(new FileOutputStream(file));

        oos.writeObject(list);
        oos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

展开
收起
爱吃鱼的程序员 2020-06-23 13:37:03 463 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    ois=newObjectInputStream(newFileInputStream(file));
    这一句返回值可能为空,或者是下一句无法读到东西;
    强转崩溃;

    list=(ArrayList<Message>)ois.readObject();不能这么转换,必须写list=newArrayList<Message>();while((obj=ois.readObject())!=null){Messagem=(Message)obj;list.add(m);}

    ois=newObjectInputStream(newFileInputStream(file));

    2020-06-23 13:37:20
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载