title: Writing to CSV in multiple columns inside a loop java
body: <p>I am trying to write a two column array to .csv file. The array has an arbitrary number of columns, ranging from a few to perhaps a few thousand. Currently I have code that writes a single array to a .csv file as follows. The parameter n in the generateCSV method represents the point in the loop, starting from n=1.</p>
  
  <pre><code>public class MakeCSVFile {
  
  public static void generateCSV(File myFile, double[][] ProtonTracking,int n) throws IOException{
      PrintWriter pw = new PrintWriter(new FileWriter(myFile));
      pw.print(String.format("Trial Number :, %d\n",  n));
      for(int i= 0; i &lt; Array.getLength(ProtonTracking); i++) {
        pw.print(String.format("%f, %f%n", ProtonTracking[i][0], ProtonTracking[i][1]));
      }
      pw.flush();  
      pw.close(); 
      }
  }
  </code></pre>
  
  <p>This code write the first array to a .csv file correctly for n=1. However, for the next stage of the loop when n=2, the array is written over the same location as for n=1, and so only the most recently arrray is saved to the .csv file. I would like to tell this method to write the array for n=2 in the two columns next to the array for n=1 etc. So that in the end the .csv file contains the array for all the n's. </p>
  
  <p>In other words, for n=2, I would like to start writing to the .csv file in column 3, not column 1. I tried to do this by using commas typed into the loop such as:</p>
  
  <pre><code>for(int k= 0; k&lt;n; k++) {
        pw.print(String.format(", ,");
      }
  </code></pre>
  
  <p>but this overwrites all the previous columns. </p>