写入CSV文件,然后在Appengine(Java)中将其压缩

我目前正在开发一个用Java做的项目,在google appengine上。

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

我想写数据并将其导出到几个csv文件,然后将其压缩,并允许用户下载它。

如果不使用任何文件类,我怎么能这样做? 我在文件处理方面不是很有经验,所以我希望你们能告诉我。

谢谢。

如果您的数据不是很大,意味着可以保留在内存中,然后导出到CSV并压缩和流式传输以供下载,这些都可以在他们的飞行中完成。 缓存可以在任何这些步骤中完成,这在很大程度上取决于应用程序的业务逻辑。

您可以创建一个zip文件,并在用户下载时添加到该文件中。 如果您使用的是servlet,那么这是一个很好的方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ..... process request // ..... then respond response.setContentType("application/zip"); response.setStatus(HttpServletResponse.SC_OK); // note : intentionally no content-length set, automatic chunked transfer if stream is larger than the internal buffer of the response ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); byte[] buffer = new byte[1024 * 32]; try { // case1: already have input stream, typically ByteArrayInputStream from a byte[] full of previoiusly prepared csv data InputStream in = new BufferedInputStream(getMyFirstInputStream()); try { zipOut.putNextEntry(new ZipEntry("FirstName")); int length; while((length = in.read(buffer)) != -1) { zipOut.write(buffer, 0, length); } zipOut.closeEntry(); } finally { in.close(); } // case 2: write directly to output stream, ie you have your raw data but need to create csv representation zipOut.putNextEntry(new ZipEntry("SecondName")); // example setup, key is to use the below outputstream 'zipOut' write methods Object mySerializer = new MySerializer(); // ie csv-writer Object myData = getMyData(); // the data to be processed by the serializer in order to make a csv file mySerizalier.setOutput(zipOut); // write whatever you have to the zipOut mySerializer.write(myData); zipOut.closeEntry(); // repeat for the next file.. or make for-loop } } finally { zipOut.close(); } } 

除非存在内存限制,否则没有理由将数据存储在文件中。 文件为您提供InputStream和OutputStream,两者都具有内存中的等价物。

请注意,创建一个csv编写器通常意味着执行类似这样的操作 ,其中的重点是获取一个数据(数组列表或映射,无论你有什么)并将其转换为byte []部分。 使用DataOutputStream等工具(如果您喜欢自己创建)或OutputStreamWriter将byte []部分附加到OutputStream中。