Pixie Pixie - 6 months ago 11
Java Question

Store an ArrayList into a csv with the rows being every two elements

I have the following array in form of ArrayList in Java:

[a, b, c, d, e, f, ...]

I want to create a csv table with the following contents i.e. rows created with two cells every two elements:

enter image description here

For now that is what I have:



public static void writeExcel(ArrayList<String> arrayList) throws Exception {

BufferedWriter writer = null;

try {

writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/Orders.csv"), "utf-8"));

for (code....)

writer.write(code ...)

} catch (IOException ex) {

} finally {

try {
writer.close();
} catch (Exception ex) {
}
}


}





Can somebody help me with the for loops?

Answer

The following loop will work:

List<String> arrayList = new ArrayList<String>();
arrayList.add("a");
arrayList.add("b");
arrayList.add("c");
arrayList.add("d");

int i = 0, size = arrayList.size();
while (i < size)
{
    String col1 = arrayList.get(i);
    String col2 = ",";
    i++;
    if (i < size)
    {
        col2 += arrayList.get(i);
    }

    writer.write(col1 + col2);

    // put a new line here
    writer.write(System.getProperty("line.separator"));

    i++; // go to the next one
}
Comments