调用readObject()时,ObjectInputStream会给出IOException

问题描述 投票:-2回答:1

我正在尝试将扩展名为.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();

这一行给出了例外。

java ioexception objectinputstream
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.