how to write csv file in google app by using java

2019-06-07 21:49发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-06-07 22:27

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

查看更多
走好不送
3楼-- · 2019-06-07 22:30

You can use OpenCSV library in Google App Engine.

查看更多
戒情不戒烟
4楼-- · 2019-06-07 22:43

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.

查看更多
登录 后发表回答