如何从文件中读取多个相同的对象

时间:2016-04-22 10:00:42

标签: java eclipse object serializable

我正在尝试使用Serializable从文件(类的相同对象)读取对象,但是当它读取所有对象时,它会给我错误IOExceptionjava.io.ObjectInputStream$BlockDataInputStream.peekByte

我正在读取对象然后保存到列表。但是当它到达时可以说EOF会引发错误。

这是我的方法:

private static void updateBook(String name) {
    // TODO Auto-generated method stub
    FileInputStream fis = null;
    ObjectInputStream in = null;
    Object obj = new Object();
    List<Object> libb = new ArrayList<Object>();
    File file = new File(name + ".ser");
    if (file.exists()) {
        try {
            fis = new FileInputStream(file);
            in = new ObjectInputStream(fis);
            try {
                while (true) {

                    obj = in.readObject();
                    libb.add(obj);
                }
            } catch (OptionalDataException e) {
                if (!e.eof) throw e;
                //JOptionPane.showMessageDialog(null, "Done!");
            } finally {
                in.close();
                //fis.close();
            }

            for(int j = 0; j < libb.size(); ++j) {
                Book li = new Book();

                 li = (Book) libb.get(j);
                System.out.println(li.getBookName());
            }
            //

        } catch (IOException e) {
            e.printStackTrace();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("\nThe file does not Exist!");
    }
}

任何人都可以告诉我如何避免来自while(true)的错误。

完成错误:

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)

2 个答案:

答案 0 :(得分:1)

try语句中,您缺少EOFException子句:

try {
    while (true) {

        obj = in.readObject();
        libb.add(obj);
    }
} catch (OptionalDataException e) {
    if (!e.eof) throw e;
    //JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
    // treat it as you like
} finally {
    in.close();
    //fis.close();
}

答案 1 :(得分:0)

你应该添加:

catch (EOFException e){
    // do stuffs
}

因为EOFException没有被捕获。