Computer Science Canada

Need help writing an ArrayList into a file

Author:  sh0td0wn [ Thu Nov 20, 2008 7:20 pm ]
Post subject:  Need help writing an ArrayList into a file

What I want to happen is that I want to print everything in my arraylist into one line in a file...
When I do that with.... the print replaces the an entry every time...

this is basically the code..

code:

for (int x = 0; x < 12; x++);
{
Object pickFName = firstNamesList.get(x);
PrintWriter write = new PrintWriter(new FileWriter("meh.txt");
write.print(pickFNAME + "  ");
write.close();
}


Instead of writing all of the entries..... it saves only the last entry...
When I tried using System.out.print (pickFNAME + " "), it worked just fine

Author:  HellblazerX [ Thu Nov 20, 2008 7:25 pm ]
Post subject:  Re: Need help writing an ArrayList into a file

There's your problem:
Java:
PrintWriter write = new PrintWriter(new FileWriter("meh.txt");

You have this inside your for loop, so every time you run this line, you'll make a new PrintWriter object, with a new FileWriter object, and a new file name "meh.txt", which will replace the last one you just made.

EDIT:
Also, that write.close () in your for loop is going to mess you up, because it'll close your file before you're even done writing everything in.

Author:  sh0td0wn [ Thu Nov 20, 2008 7:30 pm ]
Post subject:  RE:Need help writing an ArrayList into a file

Ah, that makes a lot of sense.
Thanks =)

1+


: