java - .zip 文件上传 Spring

标签 java spring request zip

我有一个分段文件上传请求。该文件是 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();
    } 

最佳答案

不要使用 FileOutputStream,而是使用 ByteArrayOutputStream 来捕获输出。然后,在 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;
}

关于java - .zip 文件上传 Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488053/

相关文章:

Angular HTTP 请求获取响应正文

java - 如何包含另一个登录页面并根据用户的 url 将用户引导至两个登录页面之一?

java - 如何使用简单的 Java 程序在 jenkins 中创建作业

java - Spring MVC 在 Google AppEngine 中初始化两次

javascript - 如何等待http请求完成? Javascript

javascript - 从 Request.js 请求方法返回结果?

java - 扩展 JMeter 定时器以可变地延迟定时器

java - Sencha CMD 7 dockerfile失败,具有非法反射访问

json - HATEOAS中 "_embedded"的含义及用法

java - IDEA中Spring注解的自动选择