我试图从JarInputStream读取文件,文件的大小返回-1.我正在从URL访问Jar文件作为inputStream.
URLConnection con = url.openConnection();
JarInputStream jis = new JarInputStream(con.getInputStream());
JarEntry je = null;
while ((je = jis.getNextJarEntry()) != null) {
htSizes.put(je.getName(),new Integer((int) je.getSize()));
if (je.isDirectory()) {
continue;
}
int size = (int) je.getSize();
// -1 means unkNown size.
if (size == -1) {
size = ((Integer) htSizes.get(je.getName())).intValue();
}
byte[] b = new byte[(int) size];
int rb = 0;
int chunk = 0;
while (((int) size - rb) > 0) {
chunk = jis.read(b,rb,(int) size - rb);
if (chunk == -1) {
break;
}
rb += chunk;
}
// add to internal resource hashtable
htJarContents.put(je.getName(),baos.toByteArray());
}
解决方法
这是记录在案的行为.
Javadoc说getSize()……
“Returns the uncompressed size of the entry data,or -1 if not kNown.”
显然,这是未知压缩数据的实际大小的情况.您的应用程序只需处理此问题.
跟进
您评论了另一个答案:
Though we have the total content size,i think with out having the individual file size we can’t read the files.
如果你没有这个大小,你仍然可以读取文件并使用ByteArrayOutputStream缓冲它,然后调用toByteArray()以将缓冲的字节提取为byte [].事实上,鉴于(根据Tom Hawtin的评论),报告的大小可能不正确,无论如何你可能应该这样做,只需将报告的大小视为提示……并将其用作ByteArrayOutputStream的初始容量.
(顺便提一下,你的问题中的代码看起来可能是以这种方式工作……从第2行到最后一行判断.问题是代码的其余部分不使用baos对象.)