Downloading a CSV File in Browser by using Java

10,829

You can read the CSV file line-by-line, and write the line on the Writer of the HttpSerlvetResponse:

public class DownloadCsvServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    final File file = new File("/tmp/data.csv");

    response.setContentType("text/csv");

    response.setHeader("Content-Disposition",
            "attachment; filename=" + file.getName());

    final BufferedReader br = new BufferedReader(new FileReader(file));
    try {
        String line;
        while ((line = br.readLine()) != null) {
            response.getWriter().write(line + "\n");
        }
    } finally {
        br.close();
    }
}

}

If you use both a Reader and a Writer, the character encoding will be handled (CSV files are text files with encoding like UTF-8 for example).

This solution streams, so only a small portion of a possibly large file is in memory.

Share:
10,829
studentcoder
Author by

studentcoder

Updated on June 04, 2022

Comments

  • studentcoder
    studentcoder almost 2 years

    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).

    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.

    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:

    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");
    }
    

    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 (http://docs.oracle.com/javaee/5/api/javax/servlet/ServletOutputStream.html), 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.

    What should I do to pass the file into the outStream?

    (Aside note: should I add this in "_response.setContentLength();", and if so, what parameters should I put into it?)

    P.s. I know that after I'm finished with outStream that I need to flush and/or close it.