Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java在内存中创建zip文件时出错_Java_Memory_Download_Zip_Zipoutputstream - Fatal编程技术网

使用Java在内存中创建zip文件时出错

使用Java在内存中创建zip文件时出错,java,memory,download,zip,zipoutputstream,Java,Memory,Download,Zip,Zipoutputstream,下面是我用来创建zip文件的代码: ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(baos); try { for(int i=0; i<docId.length; i++){ BoxDotComDocumentManager docman = new BoxDotComDocumentManager();

下面是我用来创建zip文件的代码:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
try {
    for(int i=0; i<docId.length; i++){
        BoxDotComDocumentManager docman = new BoxDotComDocumentManager();
        Document d = docman.get(docId[i]);
        ZipEntry entry = new ZipEntry(d.getFileName());
        entry.setSize(d.getFileBytes().length);
        out.putNextEntry(entry);
        out.write(d.getFileBytes());
        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename="+ "zipdemo.zip"); 
        out.closeEntry();
 }
 } catch (Exception e) {
      System.out.println("E = " + e);
 }
 try {
       resp.getOutputStream().write(baos.toByteArray());
   resp.flushBuffer();
} catch (IOException e) {
   e.printStackTrace();
    }
 finally {
baos.close();
out.close();
 }
ByteArrayOutputStream=newbytearrayoutputstream();
ZipOutputStream out=新的ZipOutputStream(BAS);
试一试{

对于(int i=0;i请尝试使用带有3个参数的out.write方法

替换:
out.write(d.getFileBytes());

与:
out.write(d.getFileBytes(),0,d.getFileBytes().length);


注意:根据java文档,只有一个参数的write方法不会被读取

将b.length字节写入此输出流

FilterOutputStream的写入方法调用其三个 具有参数b、0和b.length的参数

请注意,此方法不调用的单参数write方法 它的底层流具有单个参数b


在我自己的代码中进行此更改修复了我的问题。

一件事:当遇到致命错误时,不要只打印堆栈跟踪。使请求失败。另外,不要捕获异常。这几乎总是错误的方法。哦,为什么要在循环的每个迭代中设置头?Jon-只是尝试创建一个愉快的跟踪然后我将正确地处理所有异常,与标题相同;将它们放在循环中或外部不会改变错误。它们将被移出循环。但这使您很容易错过异常。在我看来,首先正确处理异常是值得的,这样您就可以知道何时真正通过啊,这条快乐的道路…我很感谢你的反馈;知道为什么这不起作用吗?我知道异常处理是不正确的,但这不会影响正确创建和下载此文件。