Praveen
Praveen

Reputation: 77

How to write array into file with column seperated values

I have a 2d int array. I want it to be written in a CSV file. I used the following code

BufferedWriter writer = new BufferedWriter(new FileWriter("filecsv.csv"));
for(int index11 = 0; index11 < a.length; index11++) {
    for(int subIndex1 = 0; subIndex1 < 2; subIndex1++) {
        writer.write(a[index11][subIndex1]); 
        System.out.print(",");
    }
    System.out.println();
}

My output should be like

1,2
3,4
5,6

but nothing is written in my CSV file and also in the console window nothing gets printed. Can someone tell me what I did wrong?

Upvotes: 0

Views: 479

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79877

Three problems:

  1. You're printing the numbers to the file, but the commas and newlines to the console (System.out).
  2. You're printing an additional comma at the end of each line.
  3. You need to add writer.close() at the end, otherwise the characters are just going to sit in the buffer and not get written at all.

Upvotes: 1

AJ.
AJ.

Reputation: 4534

    try{      

     BufferedWriter writer = new BufferedWriter(new FileWriter("filecsv.csv"));
           for(int index11 = 0; index11 < a.length; index11++) {
               for(int subIndex1 = 0; subIndex1 < 2; subIndex1++){
                   writer.write(String.valueOf(a[index11][subIndex1])); 
                   if(subIndex1<2-1){
                       writer.write(",");

                    }
               }
               writer.write("\n");
          }
}
    catch(IOException ex){
         ex.printStackTrace();
    }
        writer.close();

Upvotes: 0

Isaac_Zhu
Isaac_Zhu

Reputation: 105

You are just printing an array of "," to the console according to your code System.out.print(",");. Also, I doubt you should do a flush, and after you finish writing the content, you should close the writer as well as the file. Though I haven't tryied to write a csv file before, but these are common steps to write into files and save the file.

Upvotes: 0

Related Questions