
Question:
I'm currently working on a project that is done in Java, on google appengine. i have above 2000 records
Appengine does not allow files to be stored so any on-disk representation objects cannot be used. Some of these include the File class.
I want to write data and export it to a few csv files, the user to download it.
How may I do this without using any File classes? I'm not very experienced in file handling so I hope you guys can advise me.
Thanks.
Answer1:Just generate the csv in memory using a StringBuffer and then use StringBuffer.toString().getBytes()
to get a byte array which can then be sent to your output stream.
For instance if using a servlet in GAE:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
StringBuffer buffer = new StringBuffer();
buffer.append("header1, header2, header3\n");
buffer.append("row1column1, row1column2, row1column3\n");
buffer.append("row2column1, row2column2, row2column3\n");
// Add more CSV data to the buffer
byte[] bytes = buffer.toString().getBytes();
// This will suggest a filename for the browser to use
resp.addHeader("Content-Disposition", "attachment; filename=\"myFile.csv\"");
resp.getOutputStream().write(bytes, 0, bytes.length);
}
More information about <a href="https://developers.google.com/appengine/docs/java/runtime" rel="nofollow">GAE Servlets</a>
More information about <a href="http://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="nofollow">Content-Disposition</a>
Answer2:You can store data in memory using byte arrays, stings and streams. For example,
ByteArrayOutputStream csv = new ByteArrayOutputStream();
PrintStream printer = new PrintStream(csv);
printer.println("a;b;c");
printer.println("1;2;3");
printer.close();
csv.close();
Then in your Servlet you can serve your csv.toByteArray() as a stream. Some example is given here: <a href="https://stackoverflow.com/questions/1442893/file-download-servlet" rel="nofollow">Implementing a simple file download servlet</a>.
Answer3:You can use <a href="http://opencsv.sourceforge.net" rel="nofollow">OpenCSV</a> library in Google App Engine.