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");
}
}