简体   繁体   English

如何将 csv 文件转换为 ByteArrayResource

[英]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'.用户可以在“xls”和“csv”之间选择文件格式。 The export method in the spring controller, according to the specification, must return a ByteArrayResource. spring controller中的导出方法,根据规范,必须返回一个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.在服务 class 内部,我将 xls 文件转换为 ByteArrayResource 没有问题,但 csv 文件不一样。

//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[]*/);
}

Don't use anything that starts with File .不要使用以File开头的任何内容 Use ByteArrayOutputStream and an OutputStreamWriter around that:使用ByteArrayOutputStream和一个OutputStreamWriter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM