Reputation: 57
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.
Upvotes: 5
Views: 28333
Reputation: 2452
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());
}
Upvotes: 0
Reputation: 3871
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.
Upvotes: 12
Reputation: 891
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
}
Upvotes: 2
Reputation: 46398
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.
Upvotes: 4
Reputation: 3507
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.
Upvotes: 0