Reputation: 77
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
Reputation: 79877
Three problems:
System.out
).writer.close()
at the end, otherwise the characters are just going to sit in the buffer and not get written at all.Upvotes: 1
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
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