添加到ArrayList后出现NotSerializableException

时间:2015-07-26 08:37:41

标签: java serialization arraylist

所以我有这个名为World的课程:

import java.awt.event.ItemListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.ImageIcon;
public class againcheckbox extends  JFrame implements ItemListener
{
    //frame and panel
    ImageIcon image1=new ImageIcon("logo4.png");
    JFrame frame=new JFrame();
    JPanel panel=new JPanel();
    JCheckBox c1=new JCheckBox("College");
    JCheckBox c2=new JCheckBox("University");
    JCheckBox c3=new JCheckBox("Both");
    JLabel l1=new JLabel();
    public againcheckbox()
    {
        panel.add(c1);
        panel.add(c2);
        panel.add(c3);
        panel.add(l1);
        c1.setIcon(image1);
        c2.setIcon(image1);
        c3.setIcon(image1);
        c1.addItemListener(this);
        c2.addItemListener(this);
        c3.addItemListener(this);
        panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"select"));
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(200,200));
        frame.pack();
        frame.setVisible(true);
    }
    public void itemStateChanged(ItemEvent e)
    {
        JCheckBox test=(JCheckBox) e.getItem();
        String str=test.getText();
        l1.setText(str);
    }
    public static void main(String args[])
    {
        againcheckbox acb=new againcheckbox();
    }
}

我在将对象添加到public class World implements Serializable { private int dx; private int dy; private int x; private int y; private Path path; public ImageIcon image; public ArrayList<Location> locations;

之前对它进行了序列化和反序列化

现在我尝试运行序列化

ArrayList<Location> locations;

它会在此行try { FileOutputStream fos = new FileOutputStream(Main.board.worldpath.toString()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(Main.board.world.image); oos.writeObject(Main.board.world); oos.close(); }catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); }

中抛出java.io.NotSerializableException: sun.nio.fs.WindowsPath

班级位置也可序列化:

oos.writeObject(Main.board.world);

我不确定为什么它会说它不可序列化,所以序列化ArrayLists有什么特别之处吗?

1 个答案:

答案 0 :(得分:2)

问题是“路径”。 Class不可序列化。 例如,您可以将“path”保存为字符串,并在加载时创建新路径。

为它实现readObject和writeObject并使路径成为瞬态。