title: Dowload link in Java, Spring MVC
body: <p>I was trying to implement a link in my webpage to download a file as CSV. The content of the file is being appended to stringbuffer and flushed to response there itself. The code below is what i tried to achieve that : </p>
  
  <pre><code>    public void getDownloadFile(HttpServletResponse response) throws IOException{
           response.setContentType("application/octet-stream");
              response.setHeader("Content-Disposition","attachment;filename=data.csv");
              ServletOutputStream out = response.getOutputStream();
              try{
              StringBuffer sb = generateCsvFileBuffer();          
              InputStream in =  new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
              byte[] outputByte = new byte[4096];
  
              while(in.read(outputByte, 0, 4096) != -1)
              {
                  out.write(outputByte, 0, 4096);
              }
              in.close();
              out.flush();
              out.close();            
            }
          catch (Exception e) {
              System.out.println("Error in CsvFileWriter !!!");
              e.printStackTrace();
          } finally {
              try {
                  out.flush();
                  out.close();
              } catch (IOException e) {
                  System.out.println("Error while flushing/closing fileWriter !!!");
                  e.printStackTrace();
              }
          }
            return;
      }
  </code></pre>
  
  <p>And the generateCsvFileBuffer() method called is where the details for the file is written. The method is as follows:</p>
  
  <pre><code>public StringBuffer generateCsvFileBuffer(){
          StringBuffer writer = new StringBuffer();
  
          writer.append("name");
          writer.append(", ");
          writer.append("age");
          writer.append(", ");
          writer.append("address");
          writer.append(", ");
          writer.append("phone no");
          writer.append("\n");
  
          return writer;
      }
  </code></pre>
  
  <p>The programs runs till the last line of code without any error but with no output. When the link is clicked nothing happens in the view. Any help is highly appreciated.</p>