5

I just need help exporting array elements to a csv file. I don't know what's wrong with my code. Any help is gladly appreciated. Thanks.

for (int index = 0; index < cols.length; index++)
{
    FileWriter fw = new FileWriter(newFileName);
    if (index == cols.length - 1)
    {
        fw.append(cols[index]);
    }
    else
    {
        fw.append(cols[index]);
        fw.append(",");
    }

}

When I run this. Nothing happens to my csv file. Infact, it wipes everything of. Please help.

2
  • 1
    Did you do a fw.close(); at the end of your code? Also, you should declare fw outside of your loop, otherwise your file will be rewritten for each column. Commented Mar 12, 2013 at 14:46
  • What are you storing in your array? Commented Mar 12, 2013 at 14:47

5 Answers 5

12

Assuming you're storing String in your array, I post an alternative solution:

BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();

// Append strings from array
for (String element : array) {
 sb.append(element);
 sb.append(",");
}

br.write(sb.toString());
br.close();

Best regards.

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

1 Comment

so if you agree with this answer, please mark it as the right one for you in order to make this post "closed" and maybe people who have the same problem can see that this is a reliable answer to trust in. It was nice to help you. Best regards.
4

you need to flush the written data, close your FileWriter.

      finally {
        fw.close(); // close will automatically flush the data 
      }

Also, use BufferedWriter or PrintWriter instead as they are highly efficient and evolved than FileWriter.

Btw, declare the FileWriter outta your for loop. Currently it will overwrite the column for each iteration.

2 Comments

Is flush necessary? Just reading the java docs which suggest that flush is called as part of close: Closes the stream, flushing it first.
@ChrisKnight true, just realized . :)
2

If you use the more effective BufferedWriter combined with try-with-resources the writer is automatically closed. (In Java 7)

try {BufferedWriter br = new BufferedWriter(new FileWriter(newFileName)) {
    // your code
}

Comments

0

You have to use

 FileWriter fw = new FileWriter(newFileName,true);

to append content, or the file will be overwritten.

The name of the append method can be misleading, in fact it append to an internal buffer, not to the file content.

Comments

0

The best way would be to use a CSVWriter. If you have a maven project add this as a dependency:

  <dependency>
      <groupId>com.opencsv</groupId>
      <artifactId>opencsv</artifactId>
      <version>4.4</version>
  </dependency>

And then you can use it like this:

try {
        //the list that contains the String arrays
        List<String[]> whatever = new ArrayList<>();
        CSVWriter writer = new CSVWriter(new FileWriter(csvFilename));
        String[] header = "Name,Age,Height,etc..".split(",");
        writer.writeNext(header);
        writer.writeAll(whatever, true); //And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.
        writer.close();
        System.out.println("CSV file created succesfully.");
    } catch (Exception e) {
        System.out.println("exception :" + e.getMessage());
    }

Comments

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.