I have a JarInputStream (constructed from a byte array which contains a JAR file) and want to read a specific file from it. So I iterate through the containing ZipEntries and search for the file. Then I try to write the file into a byte array.
However, the file somehow isn’t read completely. If i write it to the filesystem and open it in a text editor it just contains NULLs after the first few lines which are read correctly.
The code looks like this:
JarInputStream is = new JarInputStream(new ByteArrayInputStream(_jarFile));
ZipEntry entry = is.getNextEntry();
while (entry != null) {
if (entry.getName().endsWith(".xyz")) {
// read the *.xyz file and load it into a byte array
int size = (int) entry.getSize();
byte[] _xyzFile = new byte[size];
is.read(_xyzFile, 0, size);
break;
}
entry = is.getNextEntry();
}
is.close();
The size variable definitely contains the correct number of bytes, so I don’t know why reading is stopped after just a few lines.
is.read(_xyzFile, 0, size);does not necessarily readsizebytes into the array, but up tosizebytes. The method returns the actual number of bytes read.You have to implement a loop to invoke
is.readseveral times or use any utility library offering such functionality, e.g.IOUtils.toByteArray(InputStream)from Apache Commons-IO.