I would like to allow the client to download the csv file containing the data from the ResultSet. I am using the java API (PLAY! 2.1).
My solution works, but is not used when the ResultSet contains a huge amount of data.
In my controller:
ResultSet rs = st.executeQuery(sql); String filename = ""; filename = createCSV(rs);. response().setContentType("text/csv"); response().setHeader("Content-disposition","attachment; filename="+"export.csv"); return ok(new java.io.File("D:\\UTILIS~1\\user\\AppData\\Local\\Temp\\"+filename));
createCSV method:
public static String createCSV(ResultSet _resultSet) { String filename = ""; try{ ResultSetMetaData meta = _resultSet.getMetaData(); // CSV file creation File tempDir = new File(System.getProperty("java.io.tmpdir")); System.out.println(System.getProperty("java.io.tmpdir")); File tempFile = File.createTempFile("test", ".csv", tempDir); filename = tempFile.getName(); FileWriter fileWriter = new FileWriter(tempFile, true); System.out.println(tempFile.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(fileWriter); for(int i = 1; i <= meta.getColumnCount(); i++) { String columnLabel = meta.getColumnName(i); bw.write(columnLabel + "|"); } bw.write("\r\n"); while(_resultSet.next()) { for(int i = 1, count = meta.getColumnCount(); i <= count; i++){ if (_resultSet.getObject(i) == null) bw.write("null|"); else bw.write(_resultSet.getObject(i).toString() + "|"); } bw.write("\r\n"); } bw.close(); tempFile.deleteOnExit(); } catch(Exception e){ e.printStackTrace(); } return filename; }
To save memory, how can I write a file and send it to the user using the stream.
I think I need to use Chunks, but I'm not sure how to do this.
Any samples, tips?
source share