0

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

}
BugsOverflow
  • 386
  • 3
  • 19
  • You could simplify the body of your `while` loop with [`InputStream#readAllBytes()`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/io/InputStream.html#readAllBytes()), assuming you're using Java 9+. – Slaw Jan 05 '23 at 07:29
  • @Slaw I am using 17, could you show in a comment/answer exactly where please? – BugsOverflow Jan 05 '23 at 08:10

1 Answers1

1

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;
}
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • Will try it out and leave feedback, thank you, it will give me the bytes of each entry in the zip right? or is it the bytes of all zip? – BugsOverflow Jan 05 '23 at 13:01
  • 1
    `readAllBytes()` essentially does exactly what you already have for you. It reads all the bytes until there are no more to read. And `ZipInputStream` does this per `ZipEntry`. So, it will only read the bytes of the current entry. – Slaw Jan 05 '23 at 22:36