Martin
Martin

Reputation: 277

How do I write an array to .csv in Java?

I'm trying to write a piece of code in Java that generates an array of data, and I would like to write that data to a CSV file in one single column. However, I'm struggling with getting the correct output. My program generates the population in the array

double[] wasp = new double[1000];

which is populated by one of several functions, for instance:

for (int i = 0; i < wasp.length; i++) {
                double mu = -10 + Math.random()*20;
                double sigma = 0 + Math.random()*10;
                wasp[i] = nextGaussian(mu, sigma);
                description = "Normal";
                Param1 = Double.toString(mu);
                Param2 = Double.toString(sigma);
            }

and I use the following code to try to write the array to CSV:

    FileWriter writer = new FileWriter("C:\\Users\\Havok\\Google Drive\\Skripsie\\R\\JavaOut.csv");
    
    for (int j = 0; j < wasp.length; j++) {
        writer.append((char) wasp[j]);
    writer.append(",");
    }
    writer.toString();    
    writer.flush();
    writer.close();

However, when I open the CSV file, it looks "corrupt", as if the characters weren't encoded right or something. The data also fills up much more than one column in the file.

The output I expect is a CSV file that contains a single column of real values; for instance,

1.467354

0.812738

3.595733

and so on. However, what I'm getting is a column full of something like the following:

,,,,,,￶,,,,,,,￯,ï¿¿,,￾,,,,ï¿¿,,, ,,ï¿·,,￲,￲,,ï¿·,,,,,,ï¿·,,￸,￵,,,,,,￶,,,ï¿°,￸,,ï¿»,,￾,, ,,ï¿¿,,￾,,￯,,,,￵,,ï¿»,,↓,,ï¿·,￸,,,,ï¿

What am I doing wrong? I've looked at the tutorials on Java's home site and tried to adapt other similar solutions on StackOverflow, but it seems like I'm missing something crucial.

Upvotes: 1

Views: 12668

Answers (2)

bhdrkn
bhdrkn

Reputation: 6692

Simply convert your double to string using String.valueOf(double d) method.

FileWriter writer = new FileWriter("C:\\Users\\Havok\\Google Drive\\Skripsie\\R\\JavaOut.csv");

for (int j = 0; j < wasp.length; j++) {
    writer.append(String.valueOf(wasp[j]));
    writer.append("\n");
}
writer.close();

Alternatively you can use String.format() to format your double as you wanted.

Upvotes: 3

Beryllium
Beryllium

Reputation: 566

In CSV format each set of data is delimited by a new line (\n) and each column is delimited by a comma. Therefore your code should look like this if you want a single column of data.

for (int j = 0; j < wasp.length; j++) {
    writer.append((char) wasp[j]);
writer.append("\n");
}

Upvotes: 1

Related Questions