Martyn Martyn - 1 year ago 87
Java Question

ObjectOutputStream not writing to file

I'm trying to serialize an object to file with the following:

// fill with some test data
ArrayList<Transaction> transactions = new ArrayList<>();
transactions.add(new Transaction("Internet", "2016-09-20", -28));
transactions.add(new Transaction("Groceries", "2016-09-20", -26));

//serialize transactions
try {
// File f = new File("transactions.ser");
// OutputStream file = new FileOutputStream(f);
// OutputStream buffer = new BufferedOutputStream(file);
// ObjectOutput output = new ObjectOutputStream(buffer);

File f = new File("transactions.ser");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(fos);

FileInputStream fis = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fis);
Object o = in.readObject();

catch(IOException e){
catch(ClassNotFoundException e) {

..however the IOException is being thrown. The code that is commented out does manage to create the file, but it was empty, so I assume that it's not a permissions issue? After some reading I found ObjectOutputStream but won't write to the file. What am I doing wrong?

Answer Source

verify that your class Transaction implements Serializable , you may have a type exception

I tried your code and the error that I concluded was that it did not implement the Serializable interface because without this could not convert your objects to bytes and then write them to a file

public class Transaction implements Serializable{...}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download