title: Java Spring returning CSV file encoded in UTF-8 with BOM
body: <p>Apparently for excel to open CSV files nicely, it should have the Byte Order Mark at the start. The download of CSV is implemented by writing into <code>HttpServletResponse</code>'s output stream in the controller, as the data is generated during request. I get an exception when I try to write the BOM bytes - <code>java.io.CharConversionException: Not an ISO 8859-1 character: []</code> (even though the encoding I specified is <code>UTF-8</code>). </p>
  
  <hr>
  
  <p>The controller's method in question</p>
  
  <pre><code>@RequestMapping("/monthly/list")
  public List&lt;MonthlyDetailsItem&gt; queryDetailsItems(
          MonthlyDetailsItemQuery query,
          @RequestParam(value = "format", required = false) String format,
          @RequestParam(value = "attachment", required = false, defaultValue="false") Boolean attachment,
          HttpServletResponse response) throws Exception 
  {   
      // load item list
      List&lt;MonthlyDetailsItem&gt; list = detailsSvc.queryMonthlyDetailsForList(query);
      // adjust format
      format = format != null ? format.toLowerCase() : "json";
      if (!Arrays.asList("json", "csv").contains(format)) format = "json";
  
      // modify common response headers
      response.setCharacterEncoding("UTF-8");
      if (attachment)
          response.setHeader("Content-Disposition", "attachment;filename=duomenys." + format);
  
      // build csv
      if ("csv".equals(format)) {
          response.setContentType("text/csv; charset=UTF-8");
          response.getOutputStream().print("\ufeff");
          response.getOutputStream().write(buildMonthlyDetailsItemCsv(list).getBytes("UTF-8"));
          return null;
      }
  
      return list;
  }
  </code></pre>