how to write csv file in google app by using java

点点圈 提交于 2020-01-14 03:02:55

问题


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.


回答1:


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 GAE Servlets

More information about Content-Disposition




回答2:


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: Implementing a simple file download servlet.




回答3:


You can use OpenCSV library in Google App Engine.



来源:https://stackoverflow.com/questions/13807336/how-to-write-csv-file-in-google-app-by-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!