Search code examples
javafileinputstreamzipinputstream

How does InputStream.read(byte[]) work?


I'm trying to unzip a zip folder, I have problem understand how the ZipInputStream.read(byte[]) work. This code work just fine but I don't know if my file is bigger than the buffer I set how I'll operate.

byte[] buffer = new byte[1024];
zipIs = new ZipInputStream(new FileInputStream(FILE_PATH));
while ((entry = zipIs.getNextEntry()) != null) {

        String entryName = File.separator + entry.getName();

        // Call file input stream
        FileOutputStream fos = new FileOutputStream(entryName);

        int len;
        // Write current entry
        while ((len = zipIs.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
      }

I did read the doc but I find it confusing, please help.


Solution

  • I have problem understand how the ZipInputStream.read(byte[]) work.

    It is described in the javadocs for InputStream.read(bytes[]):

    This code work just fine but i don't know if my file is bigger than the buffer i set how i'll operate.

    That is what the loop is for.

        while ((len = zipIs.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
    

    It reads one buffer at a time, setting len to the number of bytes read, until the read call returns zero (or less). Each buffer-full is written using len to say how many bytes to write, and then it repeats ...

    The while ((a = call()) > 0) { syntax is simply exploiting the fact that an assignment (e.g. (a = call())) is an expression whose value that is the value that was assigned to the variable.

    Reading streams is one situation where this idiom is commonly used. It is worth remembering it.