Java - 制作字节数组作为下载

SyA*_*yAu 3 java java-6

我有一个字节数组 (byte[]) 形式的 zip 文件,我可以使用以下命令将其写入文件系统:

        FileOutputStream fos = new FileOutputStream("C:\\test1.zip");
        fos.write(decodedBytes);  // decodedBytes is the zip file as a byte array 
        fos.close();            
Run Code Online (Sandbox Code Playgroud)

我不想将其写入文件并读取它以将其作为下载,而是想将字节数组直接作为下载,我尝试了这个,

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"File.zip\"");
    ServletOutputStream outStream = response.getOutputStream();
    outStream.write(decodedBytes);  // decodedBytes is the zip file as a byte array 
Run Code Online (Sandbox Code Playgroud)

这不起作用,我得到空文件。如何将字节数组作为下载?

更新: 我添加了finally子句并关闭了ServletOutputStream并且它起作用了。

    }catch (Exception e) {
        Log.error(this, e);
    } finally {
        try{
            if (outStream != null) {
                outStream.close();              
            }
        } catch (IOException e) {
            Log.error(this, "Download: Error during closing resources");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Pankaj 解决方案也有效。

Pan*_*boo 5

尝试以下操作:

ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");
outStream.write(decodedBytes);
outStream.flush();
Run Code Online (Sandbox Code Playgroud)