zip / gzip文件的怪异问题

时间:2018-08-20 21:45:24

标签: java zip png gzip

下面是一个程序,该程序将字节保存到.png文件并压缩到给定的名称文件夹中。

 byte[] decodedBytes = Base64.decodeBase64(contents);
                    // System.out.println(new String(decodedBytes));

                    InputStream targetStream = new ByteArrayInputStream(decodedBytes);
                    int count;
                    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilePath));
                    out.putNextEntry(new ZipEntry(pngFile));
                    byte[] b = new byte[1024];
                    while ((count = targetStream.read(b)) > 0) {
                        out.write(b, 0, count);
                    }
                    out.flush();
                    out.close();
                    targetStream.close();

当我使用7 zip手动打开它时,我看到以下文件夹结构(c:\ output \ nameofzipfile.zip \ nameofpng.png \ nameofpng)。为什么会这样呢?我究竟做错了什么?根据我的理解,这应该是结构(c:\ output \ nameofzipfile.zip \ nameofpng.png)

1 个答案:

答案 0 :(得分:0)

使用以下代码

byte []已解码= Base64.decodeBase64(contents);                 尝试(FileOutputStream fos = new FileOutputStream(zipFilePath + amazonOrderId + zipFileName)){                     fos.write(已解码);                     fos.close();                 }

            file = new File(destDirectory + amazonOrderId + pngFile);
            if (file.exists()) {
                file.delete();
            }
            try (OutputStream out = new FileOutputStream(destDirectory + amazonOrderId + pngFile)) {
                try (InputStream in = new GZIPInputStream(
                        new FileInputStream(zipFilePath + amazonOrderId + zipFileName))) {
                    byte[] buffer = new byte[65536];
                    int noRead;
                    while ((noRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, noRead);
                    }
                }
            }