File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Output while loop results to CSV Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Output while loop results to CSV" Watch "Output while loop results to CSV" New topic

Output while loop results to CSV

James Brownie

Joined: Jan 30, 2013
Posts: 3
Hello Ppls,

I have a little project that grabs some input data and then runs a while loop to generate the output,
what I would like to do is write the input data and while loop into a csv.

I know I can use the FileWriter api to append data into the csv

Just not sure how to go about getting all the while loop output into the csv.

This is what I have so far, (I have not started the csv build method yet)

Any direction would be greatly appreciated.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46424
Welcome to the Ranch

It is not usually a good idea to access CSVs directly; if you look in our FAQ (under “Excel”) you can find some libraries to write and read CSVs. At this stage, you might do well to output all your text to the command line. Then you can see its format and demonstrate the creation of the lines is working.
To write simple text, you can use a file writer, but buffer it first, or you can use a Formatter. Go through the Java Tutorials and you will find examples of both. You can wrap a File object in a Formatter and write like that. Remember you must close writers with a finally block (or try‑with‑resources); if you forget to close them, not only might the file be locked, but also you might fail to write anything. You will find links to different ways to close streams in this post. That probably refers to readers, but you can doubtless change it to close your writer.
You want to move almost that code out of the main method; it is far too long already.
I agree. Here's the link:
subject: Output while loop results to CSV
It's not a secret anymore!