Weird Java behavior with extracting zip files

I have been having these problems intermittently and so I am hoping somebody can help me. The API in this question have been based upon the answer that I received here – Java ByteBuffer for Zipfile. The very first time I extract the InputStream from the zip file everything works perfectly. I am able to extract the file and write the output to disk i.e. the method writeFileToDisk works just fine. The file size is exactly what it should be. My logic demands I need to have access to the InputStream again(there is only one entry in the zip file). So I open a new InputStream. Now when I read in the contents of the file they are all zeroes and they should not be as the file does not contain zero values.
The second problem I have is that the nested FOR loop runs every alternate time i.e. it prints out the values the first time and then when I run the program again it does not. This is java 8 on Ubuntu 14.04. At first I thought this maybe to do with the way I close the handles. I tried all possible combinations and I would like some guidance.

InputStream in = null;
InputStream in2 = null;
ByteBuffer bb;
ReadableByteChannel rbc = null;
try
    {

       ZipFile zf = new ZipFile(zipFile);
       ZipEntry entry  = zf.getEntry(fname);
       in = zf.getInputStream(entry);
       File outputFile = writeFileToDisk(fname,
                                          in,
                                          zipFile);
    //Create a new InputStream to read data into memory
       in2 = zf.getInputStream(entry);

    //Create a readable byte channel from zip input stream
    rbc =  Channels.newChannel(in2);

    //Allocate a byte buffer
    bb = ByteBuffer.allocate((int)entry.getSize());
    // Read in the data into bytebuffer via readablebytechannel
    int len =0 ;
    while (bb.hasRemaining())
        len = rbc.read(bb);
    rbc.close();
    in2.close();
    bb.flip();
    ShortBuffer sb = bb.order(ByteOrder.BIG_ENDIAN).asShortBuffer();
    for (int i=0;i<rowMax;i++)
        {
        for (int j=0;j<colMax;j++)
            {
            short value = sb.get();
            System.out.println("The value of value is " + value);
            }
        }


    }
catch (IOException ioe)
    {
    throw new Exception(ioe.getMessage());
    }
finally
    {
    close(in);
    close(in2);
    close(rbc);
    }
}


Source: java

Leave a Reply