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个回答

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

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

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐