调用readObject()时,ObjectInputStream给出IOException

时间:2019-04-29 02:59:27

标签: java ioexception objectinputstream

我正在尝试将扩展名为.dat的文件从用户确定的某个目录复制到项目目录中。当我尝试读取用户选择的已保存对象时,该程序始终会给出IOException。

File f = new File(chooser.getSelectedFile().getPath());
if(f.exists() && !f.isDirectory()) {
    FileInputStream flusso= null;
    ObjectInputStream leggiObj=null;
    try {
        flusso = new FileInputStream(chooser.getSelectedFile().getPath());
        System.out.println(chooser.getSelectedFile().getPath());
        leggiObj = new ObjectInputStream(flusso);
        if (leggiObj.readObject().getClass().equals(DatiProgresso.class)) {

            DatiProgresso dp = (DatiProgresso) leggiObj.readObject();//<----THIS LINE GIVES THE EXEPTION
            leggiObj.close();
            flusso.close();
            System.out.println("Ciao");
            FileOutputStream fop = new FileOutputStream("salvataggi/" + dp.getNome() + ".dat");
            ObjectOutputStream scriviObj = new ObjectOutputStream(fop);
            scriviObj.writeObject(dp);
            scriviObj.flush();
            fop.close();
        } else {
            JOptionPane.showMessageDialog(this, "Unacceptable file", "Error", JOptionPane.ERROR_MESSAGE);
        }
    } catch (HeadlessException ex) {
        System.out.println("HeadlessException");
        ex.printStackTrace();
    } catch (FileNotFoundException ex) {
        System.out.println("FileNotFoundException");
        ex.printStackTrace();
    } catch (IOException ex) {
        System.out.println("IOException");
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        System.out.println("ClassNotFoundException");
        ex.printStackTrace();
    }
}
}
else
{
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error" ,JOptionPane.ERROR_MESSAGE);
}
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();

此行给出了例外情况。

1 个答案:

答案 0 :(得分:0)

leggiObj.readObject().getClass().equals(DatiProgresso.class)-在这里,您从数据流中读取对象。在下一行中,您尝试从流中读取第二个对象。如果没有其他对象,则流失败。