加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 当jar文件从URL打开为InputStream时,JarEntry.getSize()

发布时间:2020-12-14 06:00:46 所属栏目:Java 来源:网络整理
导读:我试图从JarInputStream读取文件,文件的大小返回-1.我正在从URL访问Jar文件作为inputStream. URLConnection con = url.openConnection(); JarInputStream jis = new JarInputStream(con.getInputStream()); JarEntry je = null; while ((je = jis.getNextJar
我试图从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对象.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读