如何使用java在谷歌应用程序中编写csv文件 [英] how to write csv file in google app by using java

查看:98
本文介绍了如何使用java在谷歌应用程序中编写csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究一个在Java中使用google appengine完成的项目。我有超过2000条记录



Appengine不允许存储文件,因此无法使用磁盘上的任何表示形式的对象。其中一些包括File类。



我想写入数据并将其导出到几个csv文件,用户可以下载它。



如何在不使用任何File类的情况下做到这一点?我在文件处理方面不是很有经验,所以我希望你们能给我建议。

>解决方案

只需使用StringBuffer在内存中生成csv,然后使用 StringBuffer.toString()。getBytes()来获取一个字节数组然后可以发送到您的输出流。



例如,如果在GAE中使用servlet:

  protected void doGet(HttpServletRequest req,HttpServletResponse resp){
StringBuffer buffer = new StringBuffer();
buffer.append(header1,header2,header3 \\\
);
buffer.append(row1column1,row1column2,row1column3 \\\
);
buffer.append(row2column1,row2column2,row2column3 \\\
);
//将更多CSV数据添加到缓冲区

byte [] bytes = buffer.toString()。getBytes();

//这会建议浏览器使用
的文件名resp.addHeader(Content-Disposition,attachment; filename = \myFile.csv\) ;

resp.getOutputStream()。write(bytes,0,bytes.length);
}

有关 GAE Servlets



有关内容处理


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.

解决方案

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

这篇关于如何使用java在谷歌应用程序中编写csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆