.zip文件上传Spring

时间:2016-07-20 18:21:51

标签: java spring request zip

我有一个Multipart文件上传请求。该文件是zip文件.zip格式。 我如何解压缩此文件? 我需要使用每个条目的文件路径和文件内容填充Hashmap。

HashMap<filepath, filecontent>

到目前为止我的代码:

 FileInputStream fis = new FileInputStream(zipName);
 ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(fis));
 ZipEntry entry;

 while ((entry = zis.getNextEntry()) != null) {
            int size;
            byte[] buffer = new byte[2048];

            FileOutputStream fos =
                    new FileOutputStream(entry.getName());
            BufferedOutputStream bos =
                    new BufferedOutputStream(fos, buffer.length);

            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                bos.write(buffer, 0, size);
            }
            bos.flush();
            bos.close();
        }

        zis.close();
        fis.close();
    } 

1 个答案:

答案 0 :(得分:1)

使用ByteArrayOutputStream捕获输出,而不是使用FileOutputStream。然后,在对BAOS执行'close'操作之前,在其上使用'toByteArray()'方法将内容作为字节数组(或使用'toString()')。所以,你的代码应该是这样的:

public static HashMap<String, byte[]> test(String zipName) throws Exception {
    HashMap<String, byte[]> returnValue = new HashMap<>();
    FileInputStream fis = new FileInputStream(zipName);
    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(fis));
    ZipEntry entry;

    while ((entry = zis.getNextEntry()) != null) {

        int size;
        byte[] buffer = new byte[2048];

        ByteArrayOutputStream baos =
                new ByteArrayOutputStream();
        BufferedOutputStream bos =
                new BufferedOutputStream(baos, buffer.length);

        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, size);
        }
        bos.flush();
        bos.close();
        returnValue.put(entry.getName(),baos.toByteArray());
    }

    zis.close();
    fis.close();
    return returnValue;
}