I am trying to generate a .csv file as response to a restful webservice(using Jersey). So far, I am able to get a List<HashMap<String, String>> and the key should be the CSV header and value should be the CSV data.
I am using the Jackson API for CSV generation.
The code flow is:
I get the data from DAO class in
List<HashMap<String, String>>name of the list ismyArrList.
My first doubt is is this a good idea to provide the file location like this in real scenario? How else can I do this? How can I send a file with data without actually creating a file in local system?File file = new File( "C:/Users/.../Downloads/RadioObjectData.csv"); Writer writer = null; ResponseBuilder response = null; Reader reader = null; //Copy List of Map Object into CSV format at specified File location. try { writer = new FileWriter( file, false); reader = new FileReader( file); csvWriter( myArrList, writer); // csvReader( reader); response = Response.ok( (Object)file); response.header( "Content-Disposition", "attachment; filename=\"RadioObjectData.csv\""); // return response.build(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Read CSV format from specified File location and print on console.. return response.build();and now I send this
Listto thecsvWritermethod to create a.csvfile in my system so that then I can send this same file as response to the webservice.(Is this approach ok?)public static void csvWriter( List<HashMap<String, String>> listOfMap, Writer writer) throws IOException { CsvSchema schema = null; CsvSchema.Builder schemaBuilder = CsvSchema.builder(); if (listOfMap != null && !listOfMap.isEmpty()) { for (String col: listOfMap.get( 0).keySet()) { schemaBuilder.addColumn( col); } schema = schemaBuilder.build().withLineSeparator( "\r").withHeader(); } CsvMapper mapper = new CsvMapper(); mapper.writer( schema).writeValues( writer).writeAll( listOfMap); writer.flush(); }Now a
.csvfile is getting created in myCdrive at the given location.
I want this CSV to be encoded in base64 before sending it as a response.
How can I achieve all of this?