java 如何不使用ByteArrayOutputStream从ZipEntry获取字节

nhaq1z21  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(132)

有什么方法可以让这个过程简单一点吗?既然我需要每个条目的字节,有没有什么方法可以不使用ByteArrayOutputStream而获得它们

public UnzippedFile unzip(ZipFile zipFile) throws IOException {
    var unzippedFile = new UnzippedFile();
    try (ZipInputStream zipInputStream = ZipUtils.toZipInputStream(zipFile)) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            byte[] buffer = new byte[1024];
            int len;
            try (var file = new ByteArrayOutputStream(buffer.length)) {
                while ((len = zipInputStream.read(buffer)) > 0) {
                    file.write(buffer, 0, len);
                }
                unzippedFile.addFileToMap(entry.getName(), file.toByteArray());
            }
        }
    }
    return unzippedFile;
}

我的UnzippedFile类:

public class UnzippedFile {
    @Getter
    private final Map<String, byte[]> filesMap;

    public UnzippedFile() {
        this.filesMap = new HashMap<>();
    }

    public void addFileToMap(String name, byte[] file) {
        filesMap.put(name, file);
    }

}
jrcvhitl

jrcvhitl1#

如果您使用的是Java9+,那么您应该能够使用readAllBytes()简化代码。

public UnzippedFile unzip(ZipFile zipFile) throws IOException {
    var unzippedFile = new UnzippedFile();
    try (ZipInputStream zipInputStream = ZipUtils.toZipInputStream(zipFile)) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            String name = entry.getName();
            byte[] file = zipInputStream.readAllBytes();

            unzippedFile.addFileToMap(name, file);
        }
    }
    return unzippedFile;
}

相关问题