2

I'm trying to learn how to use steams and I can't seem to figure out. The thing I'm trying to do is add several separate objects to a file then retrieve them all at once. When I try to retrieve them I only get the "last" inserted object. For now I'm trying to figure out how to print the objects but later I would like to import them into an ArrayList for example. Here is my code:

public class ExpenseDB {
private final static File DB = new File("C:\\Expense2s3.dat");

public static void addExpense(Expense ex) throws AddException {
        try {
            ObjectOutputStream out;
            out = new ObjectOutputStream(new FileOutputStream(DB));
            out.writeObject(ex);
            out.close();
            System.out.println("Added "+ex);
        } catch (IOException e) {
            throw new AddException();
        }
}


@SuppressWarnings("deprecation")
public static void getAllExpenses() {
    if (DB.length() == 0) return;
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(DB));
        try {
            Expense exp=(Expense)in.readObject();
            System.out.println(exp);
            in.close();
         } catch (ClassNotFoundException e) {}
    } catch (IOException e) {
        System.err.println("Error");
    }
}
1
  • what is the issue here Commented Jun 14, 2014 at 19:20

1 Answer 1

1

When you open a file and then write to it, it will overwrite its contents. instead use new FileOutputStream(DB,true) to append to the end of the file

Sign up to request clarification or add additional context in comments.

7 Comments

Did you mean FileOutputStream?
Yep it worked :) How about the InputStream? Can I get it to loop over the objects or do I have to import them all at once?
@Airwavezx readObject() will only return one object at a time so you will have to loop to get them all.
This won't really work. Each ObjectOutputStream will output its header before writing the object. This will result is a file that consists of gibberish and can only be read by spawning ObjectInputStream in a loop, one for each object. The correct way to do this is to persist a Collection or use a structured representation like XML.
Exactly as Boris said, I tried Expense exp=(Expense)in.readObject(); while (exp != null){ which did not work. If I insist in doing it in a loop and not using a Collection how do I do that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.