java 使用里面的 csv 文件动态创建 zip

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16905599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:20:34  来源:igfitidea点击:

Creating a zip on the fly with csv files inside

javacsvzip

提问by ant-depalma

I'm trying to create a zip file on the fly containing a bunch of csv files to return from a servlet and its very confusing. A little guidance would be great. Here are chunks of code I have that somehow need to work together:

我正在尝试动态创建一个 zip 文件,其中包含一堆要从 servlet 返回的 csv 文件,这非常令人困惑。一点指导会很棒。以下是我需要以某种方式协同工作的代码块:

// output stream coming from httpResponse, thats all fine
ZipOutputStream zip = new ZipOutputStream(outputStream);


// using the openCSV library to create the csv file
CSVWriter writer = new CSVWriter(Writer?); 
// what writer do I use? I want to write to memory, not a file

writer.writeNext(entries); 
writer.close();

// at this point should I have the csv file in memory somewhere? 
//and then try to copy it into the zip file?

int length;
byte[] buffer = new byte[1024 * 32];    
zip.putNextEntry(new ZipEntry(getClass() + ".csv"));

// the 'in' doesn't exist yet - where am I getting the input stream from?
while((length = in.read(buffer)) != -1)
    zip.write(buffer, 0, length);

zip.closeEntry();
zip.flush();

回答by nadirsaghar

You can stream the ZIP file containing your CSVs as follows :

您可以流式传输包含 CSV 的 ZIP 文件,如下所示:

try {
    OutputStream servletOutputStream = httpServletResponse.getOutputStream(); // retrieve OutputStream from HttpServletResponse
    ZipOutputStream zos = new ZipOutputStream(servletOutputStream); // create a ZipOutputStream from servletOutputStream

    List<String[]> csvFileContents  = getContentToZIP(); // get the list of csv contents. I am assuming the CSV content is generated programmatically
    int count = 0;
    for (String[] entries : csvFileContents) {
        String filename = "file-" + ++count  + ".csv";
        ZipEntry entry = new ZipEntry(filename); // create a zip entry and add it to ZipOutputStream
        zos.putNextEntry(entry);

        CSVWriter writer = new CSVWriter(new OutputStreamWriter(zos));  // There is no need for staging the CSV on filesystem or reading bytes into memory. Directly write bytes to the output stream.
        writer.writeNext(entries);  // write the contents
        writer.flush(); // flush the writer. Very important!
        zos.closeEntry(); // close the entry. Note : we are not closing the zos just yet as we need to add more files to our ZIP
    }

    zos.close(); // finally closing the ZipOutputStream to mark completion of ZIP file
} catch (Exception e) {
    log.error(e); // handle error
}