2012-03-09 71 views
0

我有一个名为“san.jar”与各种文件夹,如“类”,“资源”等的jar文件, 说例如我有一个像“资源/资产/图像“,其中有各种图像,我没有任何关于他们的信息,如图像的名称或文件夹下的图像数量,因为jar文件是私人的,我不允许解压缩jar。阅读给定具体路径的jar文件的内容

OBJECTIVE:我需要获取给定路径下的所有文件,而不必遍历整个jar文件。

现在我正在做的是遍历每一个条目,每当我遇到.jpg文件,我执行一些操作。 这里只是读取“resources/assets/images”,我遍历整个jar文件。

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文件,我执行一些操作。 这里只是读取“resources/assets/images”,我遍历整个jar文件。

+1

它是'em.nextElement()'或'em1.nextElement()'? – Rakesh 2012-03-09 07:23:46

+0

*“现在我所做的是遍历每一个条目,并且每当我遇到.jpg文件时,我都会执行一些操作。”*为什么不读取它们并缓存信息? – 2012-03-09 07:44:27

+0

对不起,它的时间,而不是em1。 – 2012-03-09 08:00:37

回答

0

此代码的工作你的目的

JarFile jarFile = new JarFile("my.jar"); 

    for(Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements();) { 
     String s= em.nextElement().toString(); 

     if(s.startsWith(("path/to/images/directory/"))){ 
      ZipEntry entry = jarFile.getEntry(s); 

      String fileName = s.substring(s.lastIndexOf("/")+1, s.length()); 
      if(fileName.endsWith(".jpg")){ 
       InputStream inStream= jarFile.getInputStream(entry); 
       OutputStream out = new FileOutputStream(fileName); 
       int c; 
       while ((c = inStream.read()) != -1){ 
        out.write(c); 
       } 
       inStream.close(); 
       out.close(); 
       System.out.println(2); 
      } 
     } 
    } 
    jarFile.close(); 
+0

嗨Rakesh, 感谢您的回复。但是你不觉得,你正在使用和我一样的逻辑吗?你将它与“startsWith()”进行比较,而我将它与做相同操作的“conatins()”进行比较。但是,在这两种情况下,它都遍历整个jar文件。 – 2012-03-09 09:49:00

+0

我不认为你可能没有迭代通过整个JAR文件.... – Adam 2012-03-09 10:06:47

+0

@SanthoshRaj,是的我同意,好吧,你遍历每个目录中的每个文件,并检查文件名是否结束与.jpg。在我的代码中,我只在需要的目录中迭代文件。所以这减少了迭代次数。 – Rakesh 2012-03-09 10:16:21

0

这可以用一个正则表达式简明得多做......它也将在JPG文件有大写扩展JPG工作。

JarFile jarFile = new JarFile("my.jar"); 

Pattern pattern = Pattern.compile("resources/assets/images/([^/]+)\\.jpg", 
     Pattern.CASE_INSENSITIVE); 

for (Enumeration<JarEntry> em = jarFile.entries(); em 
     .hasMoreElements();) { 
    JarEntry entry = em.nextElement(); 

    if (pattern.matcher(entry.getName()).find()) { 
     BufferedImage image = ImageIO.read(jarFile 
       .getInputStream(entry)); 
     System.out.println(image.getWidth() + " " 
       + image.getHeight()); 

    } 
} 
jarFile.close(); 
+0

迭代整个罐子?这可以在没有迭代整个罐子的情况下完成吗? – Rakesh 2012-03-09 10:54:38

+0

是的,就像你的解决方案:) – Adam 2012-03-09 11:01:53

0

利用Java 8和文件系统现在是很容易的,

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将只搜索提供的路径了所需的深度。