2

I currently have the arraylist from the resultset and I use openCSV library to print as a CSV.

ArrayList<Integer> arlist=new ArrayList<Integer>();
for(i=1;i<30;i++){
 for(k=1;k<100;k++){

       String sql="select count(id) where day=?"
       PreparedStatement pstmt=conn.prepareStatement(sql);
       pstmt.setInt(1,k);
       ResultSet rs=rs.getInt(1);
       int count=rs.getInt(1); 
       arlist.add(count);
   }


   CSVWriter writer=new CSVWriter(new FileWriter("/home/user/file"+i+".csv"),',')
   writer.writeNext(arlist.toArray(new String [0]));
   writer.close();
   arlist.clear();
}

But the problem is the CSV is a 1 line CSV with 100 columns.Instead of this I need a 100 line CSV with 1 column.(size of array list is 100).Any help is Appreciated.

Eran
  • 387,369
  • 54
  • 702
  • 768
RKR
  • 657
  • 3
  • 13
  • 26

1 Answers1

1

It looks like each array you pass to writeNext() becomes a single row in the CSV, so you need a loop that calls writeNext() for each element of your List :

CSVWriter writer = new CSVWriter(new FileWriter("/home/user/file" + i + ".csv"),',') ;
for (Integer i : arlist) {
    writer.writeNext(new String[]{i.toString()});
}
writer.close();
arlist.clear();

Of course, since you only have one column in each line, you can skip using that CSVWriter class and just dump each element of the List to a separate line of the output file.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • arlist is a Integer array list and how can u loop by a String? – RKR Jan 19 '17 at 09:42
  • The method 'writeNext' allows only String[ ] as it's argument – RKR Jan 19 '17 at 09:49
  • @RKR OK, in that case, converting each Integer of the List to a String[] will work. I did fix another typo. – Eran Jan 19 '17 at 09:52
  • I used the above method but did not work.i also tried `for (Integer i : arlist) { String [] y=new String[1]; y[0]=x.toString();writer.writeNext(new String[]{i.toString()}); }`But did not work – RKR Jan 19 '17 at 10:22
  • @RKR What output do you get? – Eran Jan 19 '17 at 10:25
  • Yeah which I commented above worked.The problem was which I had the writer.writeNext two times.Now it worked like a charm – RKR Jan 19 '17 at 10:29