Search code examples
javabytefileoutputstream

How to convert csv file to ByteArrayResource


I'm working on a data export. The user can choose the file format between 'xls' and 'csv'. The export method in the spring controller, according to the specification, must return a ByteArrayResource. Inside the service class I had no problem to convert the xls file to a ByteArrayResource but it is not the same for the csv file.

//INSIDE SERVICE BUSINESS LOGIC

public ByteArrayResource generateCsvFile(){

   FileWriter csvWriter = new FileWriter("myFileName.csv");

   //here some logic to build my csv file

   /* I AM NOT ABLE TO CONVERT THE FileWriter IN byte[] IN ORDER TO RETURN IT TO THE CONTROLLER
      I ALSO TRIED TO CONVERT IT TO FileOutputStream OR ANYTHING THAT CAN USE SOMETHING LIKE 
      .getByte() or toByte() BUT I'M NOT FINDING OUT ANY SOLUTIONS */

   return new ByteArrayResource(/*file converted in byte[]*/);
}

Solution

  • Don't use anything that starts with File. Use ByteArrayOutputStream and an OutputStreamWriter around that:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (Writer writer = new OutputStreamWriter(out)) {
      // write to writer
    }
    return new ByteArrayResource(out.toByteArray());