希尔瓦娜斯控
2016-04-25 00:50
采纳率: 37.5%
浏览 2.0k
已采纳

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();
    }

}

}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 恋恋西风 2016-04-25 01:07
    已采纳

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

    已采纳该答案
    打赏 评论
  • threenewbee 2016-04-25 01:06
     list=(ArrayList<Message>) ois.readObject();
    不能这么转换,必须写
    list=new ArrayList<Message>();
    while((obj=ois.readObject())!=null) { 
                    Message m = (Message)obj; 
                    list.add(m);
                } 
    
    打赏 评论
  • gavin-sun 2016-04-25 06:08

    ois=new ObjectInputStream(new FileInputStream(file));

    打赏 评论

相关推荐 更多相似问题