title: how to avoid use of toString().getBytes("UTF-8") to avoid OOM error? Is there any better approach to convert to byte[] from StringWriter?
body: <p>I have a reporting web application which generates reports. The application gets data from a database and stores data into a <code>StringWriter</code> object. I have to get this data in a byte array format to create a csv file and send it to browser.</p>
  
  <p>Below is the code snippet</p>
  
  <pre><code> return new FileTransfer(fileName, reportType.getMimeType(),
                      new ByteArrayInputStream(generateCSV(reportType, grid, new DataList(), params).toString().getBytes("UTF-8")));
  </code></pre>
  
  <p>where <code>generateCSV</code> returns a <code>StringWriter</code> object, then to convert it into byte array I am calling <code>toString</code> and then <code>getBytes()</code> method. Below is what the <code>generateCSV</code>  method looks like</p>
  
  <pre><code>StringWriter generateCSV(ReportType reportType, GridConfig grid, DataList dataList, String params) {......}
  </code></pre>
  
  <p>The problem is that when my report has huge records (more than 1 million), the <code>getBytes()</code> method fails with </p>
  
  <blockquote>
    <p>java.lang.OutOfMemoryError: Requested array size exceeds VM limit</p>
  </blockquote>
  
  <p>The whole report data when converted to String object has a huge number of characters (billions of it). The <code>.getBytes("UTF-8")</code> method convert it into array, each array element as one character. And for 1 million records, the character are exceeding the MAX JVM ARRAY size limit (<a href="https://plumbr.io/outofmemoryerror/requested-array-size-exceeds-vm-limit" rel="nofollow noreferrer">https://plumbr.io/outofmemoryerror/requested-array-size-exceeds-vm-limit</a>).</p>
  
  <p>Now how can I avoid use of <code>toString().getBytes("UTF-8")</code> to avoid OOM error? Is there any better approach to convert to byte array from <code>StringWriter</code>?</p>