如何将字节数组的映射写入ZIP文件

时间:2018-02-22 05:25:53

标签: java zip

我正在尝试将String和byteArray的映射写入zip文件,而不创建物理文件本身。 String将是文件的名称。我设法创建了zip,但创建的zip文件中的文件有0个字节

public void zipFiles2(Map<String, byte[]> inMap) {

        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        try {
            fos = new FileOutputStream("C:\\Desktop\\testing1.zip");
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            for (Map.Entry<String, byte[]> pair : inMap.entrySet()) {
                ZipEntry entry = new ZipEntry(pair.getKey());
                System.out.println("Zipping the file: " + pair.getKey());
                entry.setSize(pair.getValue().length);
                zos.putNextEntry(entry);
                byte[] tmp = new byte[4 * 1024];
                int size = 0;
                zos.write(tmp, 0, size);
                zos.flush();

            }
            zos.close();
            System.out.println("Done... Zipped the files...");
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception ex) {

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

ZipEntry entry = new ZipEntry(pair.getKey());
entry.setSize(pair.getValue().length);
zos.putNextEntry(entry);
zos.write(pair.getValue());
zos.flush();

您从空int size = 0;byte[])中写出零字节(byte[] tmp = new byte[4 * 1024];)而不是Map中的字节。