为什么我不能从ObjectInputStream中读取ArrayList?

时间:2014-12-02 23:25:59

标签: java serialization objectinputstream

我正在读取和写入磁盘的对象。为什么"保存"方法工作,但当我尝试"加载"方法,系统挂起?我保持读/写字节的一致性。

" System.out.println"的输出" load"中的方法方法是:415301485而不是3。

如果我从数组中删除保存和加载,一切正常。

我在我的智慧结束时,几乎想要放弃并尝试别的东西。任何帮助将不胜感激。

非常感谢!

public class MyClass {
    private String name = "test";
    private int number = 99;
    private BufferedImage image = null;
    private ArrayList<BufferedImage> imageArray = new ArrayList<BufferedImage>();

    public MyClass() {
        try {
        // Load single image
        this.image = ImageIO.read(FileIO.class.getResource("/assets/logo.png"));

        // Add a bunch of images to the array
        imageArray.add(ImageIO.read(this.getClass().getResource("/test/1.png")));
        imageArray.add(ImageIO.read(this.getClass().getResource("/test/2.png")));
        imageArray.add(ImageIO.read(this.getClass().getResource("/test/3.png")));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void save(String filename) {


    try {
        FileOutputStream fout = new FileOutputStream(filename);
        ObjectOutputStream oos = new ObjectOutputStream(fout);

        // Default objects
        oos.writeObject(name);
        oos.writeInt(number);

        // Single image
        ImageIO.write(image, "png", oos);

        // Number of images in array
        oos.writeInt(imageArray.size());

        // Each image
        for (BufferedImage image: imageArray){
            ImageIO.write(image, "png", oos);
        }

        oos.close();
        fout.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

public void load(String filename) {

    try {
        FileInputStream fin= new FileInputStream(filename);
        ObjectInputStream ois = new ObjectInputStream(fin);

        // Default objects
        this.name = (String) ois.readObject();
        this.number = ois.readInt();

        // Single image
        this.image = ImageIO.read(ois);

        // Array of images
        int imageCount = ois.readInt();
        System.out.println(imageCount);
        for (int i=0; i<imageCount; i++){
            this.imageArray.add(ImageIO.read(ois));
        }

        ois.close();
        fin.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

0 个答案:

没有答案