Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export array values to csv file java

Tags:

java

arrays

csv

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.

like image 366
user2026615 Avatar asked Mar 12 '13 14:03

user2026615


People also ask

How do I write an array to a CSV file?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

Where do I put CSV files in eclipse?

Click File > Import. In the Import window, click Team > Work Items from CSV. Click Next. Click Browse and select the CSV file to import.

What is CSV file in Java?

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java.


2 Answers

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.

like image 128
Marcelo Tataje Avatar answered Oct 13 '22 07:10

Marcelo Tataje


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.

like image 21
PermGenError Avatar answered Oct 13 '22 07:10

PermGenError