title: Downloading a CSV File in Browser by using Java
body: <p>I'm trying to add a button on a web application which when clicked, downloads a CSV file (which is tiny, only about 4KB in size). </p>
  
  <p>I already have the button made and a listener attached to it. The file is also ready. 
  The only thing I need to do now is create the actual event that downloads the csv file when the button is clicked.</p>
  
  <p>Assuming that "file" (which is of type File) is the name of the csv file that I'm using, and that it's ready to go, this is the method I have so far:</p>
  
  <pre><code>public void downloadCSV(HttpServletRequest _request, HttpServletResponse _response, LogFileDetailCommand cmd) throws Exception {
       ServletOutputStream outStream = _response.getOutputStream();
       _response.setContentType("text/csv");  
       _response.setHeader("Content-Disposition", "attachment; filename=data.csv");
  }
  </code></pre>
  
  <p>I realise that I'm missing the part that writes the file to the ServletOutputStream but this is the part that I'm stuck on. I know that class ServletOutputStream extends class OutputStream (<a href="http://docs.oracle.com/javaee/5/api/javax/servlet/ServletOutputStream.html" rel="nofollow">http://docs.oracle.com/javaee/5/api/javax/servlet/ServletOutputStream.html</a>), and therefore it has inherited its "write" methods, so in an ideal world I'd like to simply say "outStream.write(file);", but I can't do that seeing as these "write" methods only have either byte, byte[] and int as the parameters, and it's not possible to pass a File into them.</p>
  
  <p>What should I do to pass the file into the outStream?  </p>
  
  <p>(Aside note: should I add this in "_response.setContentLength();", and if so, what parameters should I put into it?)</p>
  
  <p>P.s. I know that after I'm finished with outStream that I need to flush and/or close it.</p>