首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JarFile / ZipFile缓存?

JarFile / ZipFile缓存?
EN

Stack Overflow用户
提问于 2011-06-08 16:01:05
回答 1查看 544关注 0票数 1

我需要从我的应用程序验证一个签名的jar。我发现我可以通过阅读所有内容来做到这一点,如下所示:

代码语言:javascript
复制
public boolean verifyJar(String filePath) {
    try {
        JarFile jar = new JarFile(filePath, true);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            InputStream is = jar.getInputStream(entry);
            byte[] buffer = new byte[10000];
            while (is.read(buffer, 0, buffer.length) != -1) {
                // we just read. this will throw a SecurityException
                // if a signature/digest check fails.
            }
            is.close();
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

如果我使用有效的jar执行检查器,它就会通过。如果我把罐子切成两半来损坏它,它就失败了。但是如果我在一个进程中同时执行这两个操作,第二次检查就会通过(就像它读取文件的前一个版本一样)!

代码语言:javascript
复制
public static void main(String[] args) throws Exception {
    String path = "src/test/resources/temp/lib.jar";
    // Passes - that's good
    System.out.println(new Validator().verifyJar(path));

    byte[] content = FileUtil.readFile(path);
    FileUtil.save(path, Arrays.copyOf(content, content.length / 2));
    // Passes - but it shouldn't.
    // Fails if the first check is commented out though.
    System.out.println(new Validator().verifyJar(path));
}

因此,看起来ZipFileJarFile是以某种方式缓存的。如何抑制此行为?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-08 16:25:55

ZipFile必须关闭,这样本机代码才不会缓存。如果路径和File.lastModified相同,Iirc ZipFile会包装相同的句柄(jzfile)。

或者,触摸File.lastModified也可以做到这一点,但手动关闭任何打开的东西(包括。ZipFile)对于防止资源泄漏是必要的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6275838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档