Home > Enterprise >  Memory with readAllBytes and read
Memory with readAllBytes and read

Time:11-14

I have a situation with ZIP-archives and idk what's better method for unpacking.

I correctly understand that if we will use InputStream.readAllBytes() and next OutputStream.write(ourAllBytes) - that bad practice (if arhive have file < 2gb, for example), and i need use fixed count of bytes for reading and writing (InputStream.read(buffer) and OutputStream.write(buffer, 0 len)) for saving RAM? What's better for my situation?

CodePudding user response:

To avoid reading and storing all input bytes in memory you can use InputStream.transerTo(OutputStream) method:

try (var in = CreateYourInputStreamHere;
     var out = CreateYourOutputStreamHere) {
  in.transferTo(out);
}

In Java 17 this approach will do it with an 8K buffer, reading and writing a single 8K chunk of data before processing next chunk.

  • Related