Question

I need to take a list of Objects and write their instance variables to a text file. It would look something like this:

Hot Dog,1.25,Grocery Store
Gas,42.15,Gas Station
etc.

I have some code that looks like this:

public void writeListToFile(String fileName, ArrayList<BudgetItem> writeList) throws Exception {
    PrintWriter out = null;
    for(int i = 0; i<writeList.size(); i++) {   
        if(writeList.get(i) instanceof Expense) {
            Expense writeExpense = (Expense) writeList.get(i);
            try {
                out = new PrintWriter(new FileWriter(fileName));
                dump(out, writeExpense);
            }
            finally {
            }
        }
        else if(writeList.get(i) instanceof Income) {
            Income writeIncome = (Income) writeList.get(i);
            try {
                out = new PrintWriter(new FileWriter(fileName));
                dump(out, writeIncome);
            }
            finally {
            }
        }
    }
    out.close();
}

public void dump(PrintWriter out, Expense writeExpense) {
    out.print(writeExpense.getDateOfTransaction().get(GregorianCalendar.YEAR));
    out.print(",");
    out.print(writeExpense.getDateOfTransaction().get(GregorianCalendar.MONTH));
    out.print(",");
    out.print(writeExpense.getDateOfTransaction().get(GregorianCalendar.DATE));
    out.print(",");
    out.print(writeExpense.getItemName());
    out.print(",");
    out.print(writeExpense.getMethodOfPay());
    out.print(",");
    out.print(writeExpense.getPlaceOfPurchase());
    out.print(",");
    out.print(writeExpense.getQuantity());
    out.print(",");
    out.print(writeExpense.getPrice());
    out.print("\n");
}

and one other method similar to the 2nd one.

When I run it, it only writes out one line, the first object in the list, and nothing else. I can't figure out what's going on. I know object serialization is a faster option, but for this project, since I am still learning, I want to use this way.

Main method as requested by one of the answers:

public static void main(String[] args) throws Exception {
    String itemName = "Hot Dog";
    int quantity = 1;
    String placeOfPurchase = "Weiner Stand";
    String methodOfPay = "Credit";
    BigDecimal price = new BigDecimal(1.25);
    GregorianCalendar g = new GregorianCalendar(2013,11,1);
    Expense e = new Expense(g, price, itemName, quantity, placeOfPurchase, methodOfPay);
    BudgetItem bi = (BudgetItem) e;
    String itemName2 = "Gun";
    int quantity2 = 1;
    String placeOfPurchase2 = "Weiner Stand";
    String methodOfPay2 = "Credit";
    BigDecimal price2 = new BigDecimal(1.25);
    GregorianCalendar g2 = new GregorianCalendar(2013,11,1);
    Expense e2 = new Expense(g, price, itemName, quantity, placeOfPurchase, methodOfPay);
    BudgetItem bi2 = (BudgetItem) e2;
    ArrayList<BudgetItem> abi = new ArrayList<BudgetItem>();
    abi.add(bi);
    abi.add(bi2);
    RegisterFileIO rfio = new RegisterFileIO();
    rfio.writeListToFile(System.getProperty("user.dir") + "/data.out", abi);


    BufferedReader in = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/data.out"));
    Scanner lineScanner = new Scanner(in);
    lineScanner.useDelimiter(",");
    while(lineScanner.hasNext()) {
        System.out.println(lineScanner.next());
    }
}
Was it helpful?

Solution

I believe the problem is you creating a new PrintWriter each iteration. You should declare it outside the loop. What is happened is that when a new PrintWriter is created it overwrites the previous data stored in the file.

PrintWriter out = null;
try {
    out = new PrintWriter(new FileWriter(fileName));
    for(int i = 0; i<writeList.size(); i++) {   
        if(writeList.get(i) instanceof Expense) {
            Expense writeExpense = (Expense) writeList.get(i);

            dump(out, writeExpense);
    }
 } finally {
 }

OTHER TIPS

This is because you're instantiating a new PrintWriter object (and a new FileWriter object) for each object in your list.

You should instantiate it only once, before the for loop. Replace

PrintWriter out = null;

with

PrintWriter out = new PrintWriter(new FileWriter(fileName));

Just a side note: with your current code, you might end up with a NullPointerException at line out.close(); if your ArrayList is empty.

First: you are writing java, not C++. Use Java structures and techniques.

As mentioned by MadConan, your implementation is overkill. Use toString() (or toBlammy() - blammy being something other than string) on each object type (Expense and Income) to format the output.

Hint: anytime you have a bunch of if (instanceof blammy) you should consider polymorphism instead.

You code should look something like this:

public void writeListToFile(
    final String fileName,
    final List<BudgetItem> listBudgetItem)
throws Exception
{
    PrintWriter out = null;

    try
    {
        out = new PrintWriter(new FileWriter(fileName));
        for(BudgetItem current : listBudgetItem)
        {
            out.println(current.toBlammy());
        }
    }
    catch (... exceptions)
    {
    }
    finally
    {
        // close the PrintWriter.
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top