给定特定路径的jar文件的内容 [英] Read contents of jar file given specific path

查看:140
本文介绍了给定特定路径的jar文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为san.jar的jar文件,其中包含各种文件夹,如类,资源等,
比如说我有一个像资源/资产/图像这样的文件夹结构有各种各样的图像,我没有任何关于它们的信息,如图像的名称或文件夹下的图像数量,因为jar文件是私有的,我不允许解压缩jar。

I have a jar file named "san.jar" with various folders like "classes", "resources", etc., Say for e.g i have a folder structure like "resources/assets/images" under which there are various images which I do not have any information about them like name of the images or number of images under the folder as the jar file is private and I am not allowed to unzip the jar.

目标:我需要获取给定路径下的所有文件而不迭代整个jar文件。

OBJECTIVE: I need to get all the files under the given path without iterating over the whole jar file.

现在我正在做的是遍历每个条目,每当我遇到.jpg文件时,我都会执行一些操作。
这里只读资源/资产/图像,我正在遍历整个jar文件。

Right now what I am doing is iterating through each and every entry and whenever i come across .jpg file, I perform some operation. Here for reading just the "resources/assets/images", I am iterating through the whole jarfile.

JarFile jarFile = new JarFile("san.jar");  
for(Enumeration em = jarFile.entries(); em.hasMoreElements();) {  
                String s= em.nextElement().toString();  
                if(s.contains("jpg")){  
                   //do something  
                }  
 }  

现在我正在做的是遍历每个条目,每当我遇到.jpg文件时,我都会执行一些操作。
这里只读资源/资产/图像,我正在遍历整个jar文件。

Right now what I am doing is iterating through each and every entry and whenever i come across .jpg file, I perform some operation. Here for reading just the "resources/assets/images", I am iterating through the whole jarfile.

推荐答案

使用Java 8和文件系统现在非常简单,

With Java 8 and filesystems it is pretty easy now,

Path myjar;
try (FileSystem jarfs = FileSystems.newFileSystem(myjar, null)) {
   Files.find(jarfs.getPath("resources", "assets", "images"), 
              1, 
              (path, attr) -> path.endsWith(".jpg"),
              FileVisitOption.FOLLOW_LINKS).forEach(path -> {
            //do something with the image.
    });
}

Files.find只会搜索提供的路径,达到所需的深度。

Files.find will only search the provided path up the the desired depth.

这篇关于给定特定路径的jar文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆