Search code examples
javazipinputstream

How to get bytes from ZipEntry without using ByteArrayOutputStream


Is there a way to make this a little simpler? Since I need the bytes of each entry is there any way to get them without using the 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;
}

My UnzippedFile class:

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);
    }

}

Solution

  • If you're using Java 9+ then you should be able to simplify that code with 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;
    }