Reputation: 1
I am having a problem writing an ArrayList
to a File
in java. The program below is saving an error to the file instead of the data I am trying to save.
Below is the code I am using. Can anyone point out what I am doing wrong?
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());
}
}
Upvotes: 0
Views: 194
Reputation: 424993
A. Contact
must implement Serializable
(you haven't shown code for Contact
)
B. Don't serialize each Contact
, just serialize the whole List
Upvotes: 2