title: Dynamically writing to CSV during loop
body: <p>I am working with a gigantic loop in a <code>static void main(String[] args)</code>. This loop manipulates some numeric primitives that I want to get into a CSV, where each row in the CSV corresponds to an iteration in the loop.</p>
  
  <p>My objective is to dynamically write these primitives such that at the end of each iteration they can be garbage collected and essentially forgotten about. The worst thing would be to have these stored in memory until the end of the loop, since the loop is very long. </p>
  
  <p>I have written a class that attempts to do this, which is pasted below. <strong>Question</strong>: <em>Is each row of the CSV being stored into memory and then written to disk at the end of the loop? If so, how do I make it such that disk writing happens at every loop iteration to free up memory (preferably in a way that is fast)?</em></p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      WriteCSV csvWriter = new WriteCSV("src","Hello.csv")
  
      for(int i = 0 ; i &lt; 1000 ; ++i) { //Much bigger in real-world case
          csvWriter.writeRow(i);
      }
      csvWriter.close(); //Does all i between {1,2,...,1000} get GC'd here or dynamically in the above loop???
  }
  </code></pre>
  
  <p>CSV writing class to write dynamically in a loop:</p>
  
  <pre><code>class WriteCSV {
      private FileWriter fstream;
      private BufferedWriter out;
  
  
      public WriteCSV(String directory, String filename) throws IOException {     
          File file = new File(directory, filename);
  
          this.fstream = new FileWriter(file);
          this.out = new BufferedWriter(this.fstream);
      }
  
  
      public void writeRow(int newRow) throws IOException {
          this.out.write(String.valueOf(newRow));
          this.out.newLine();
      }
  
      public void close() throws IOException {
          this.out.close();
      }
  
  }
  </code></pre>