代码之家  ›  专栏  ›  技术社区  ›  ivan_ivanovich_ivanoff

(在运行时)读取JAR文件的内容?[复制品]

  •  1
  • ivan_ivanovich_ivanoff  · 技术社区  · 16 年前

    这个问题已经有了答案:

    我读过这些帖子:

    Viewing contents of a .jar file

    How do I list the files inside a JAR file?

    但遗憾的是,我找不到一个很好的解决办法 阅读 JAR的内容(逐文件)。

    此外,是否有人能给我一个提示,或指向一个资源,在那里讨论我的问题?

    我只是想了个不太直接的方法:
    我可以将jar的资源列表转换为 内部JAR URL,然后我可以使用OpenConnection()打开它。

    3 回复  |  直到 13 年前
        1
  •  8
  •   NawaMan    16 年前

    你用 JarFile 打开JAR文件。使用它,您可以通过使用“getentry(string name)”或“entires”获得zipEntry或jarEntry(它们可以被视为相同的东西)。一旦你得到一个条目,你可以使用它通过调用' JarFile.getInputStream(ZipEntry ze) '.你可以从流中读取数据。

    见教程 here .

        2
  •  3
  •   ZZ Coder    16 年前

    以下是我如何将其作为zip文件读取的,

       try {
            ZipInputStream is = new ZipInputStream(new FileInptuStream("file.jar"));
            ZipEntry ze;
    
            byte[] buf = new byte[4096];
            int len;
    
            while ((ze = is.getNextEntry()) != null) {
    
                System.out.println("----------- " + ze);
                len = ze.getSize();
    
                // Dump len bytes to the file
                ...
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    如果要解压缩整个文件,这比jarfile方法更有效。

        3
  •  2
  •   Stephan    13 年前

    下面是读取JAR文件中所有文件内容的完整代码。

    public class ListJar {
        private static void process(InputStream input) throws IOException {
            InputStreamReader isr = new InputStreamReader(input);
            BufferedReader reader = new BufferedReader(isr);
            String line;
    
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        }
    
        public static void main(String arg[]) throws IOException {
            JarFile jarFile = new JarFile("/home/bathakarai/gold/click-0.15.jar");
    
            final Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                final JarEntry entry = entries.nextElement();
                if (entry.getName().contains(".")) {
                    System.out.println("File : " + entry.getName());
                    JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
                    InputStream input = jarFile.getInputStream(fileEntry);
                    process(input);
                }
            }
        }
    }