将ArrayList写入File的异常

时间:2012-04-03 17:11:48

标签: java

我在java中将ArrayList写入File时遇到问题。下面的程序将错误保存到文件而不是我试图保存的数据。

以下是我正在使用的代码。谁能指出我做错了什么?

package mytracker;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import javax.swing.JOptionPane;

public class ExportContacts 
{
    private ObjectOutputStream OP;

    private void openFileOut(String path)
    {
        try
        {
            OP = new ObjectOutputStream(new FileOutputStream(path + ".dat"));
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }

    private void AddContacts(List<Contact> contacts)
    {
        try
        {
            for(int i=0;i<contacts.size();i++)
            {
                OP.writeObject(contacts.get(i));
            }
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }

    private void CloseFileOut()
    {
        try 
        {
            if(OP!=null)
                OP.close();
        }
        catch (IOException e) 
        {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }

    public void ExportConacts(String path,List<Contact> contacts)
    {
        openFileOut(path);
        AddContacts(contacts);
        CloseFileOut();
    }
}

private void ExportButtonMouseClicked(java.awt.event.MouseEvent evt) 
{
    try
    {             
        JFileChooser fileChooser=new JFileChooser();
        //fileChooser.setFileFilter(new filter());
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result=fileChooser.showSaveDialog(this);

        if(result!=JFileChooser.CANCEL_OPTION)
        {
            String path= fileChooser.getSelectedFile().getPath();
            ExportContacts ex=new ExportContacts();
            //CL is object of the class that save the contacts
            List<Contact> c=CL.getContactsList();
            ex.ExportConacts(path, c);
            JOptionPane.showMessageDialog(null, "Contacts Exported Successfully !");
        }
    }
    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:2)

一个。 Contact必须实施Serializable(您尚未显示Contact的代码)
B.不要序列化每个Contact,只是序列化整个List