如何编写可以提取JAR文件并将其数据存储在指定目录(位置)的Java程序? [英] How to write a Java program which can extract a JAR file and store its data in specified directory (location)?

查看:162
本文介绍了如何编写可以提取JAR文件并将其数据存储在指定目录(位置)的Java程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 JAR 文件。现在,我创建了另一个Java程序。我想在其他目录中解压缩那个JAR文件,这意味着我想做一些像解压缩的事情。

I have created a JAR file. Now, I created another Java program. I want to unpack that JAR file in some other directory, meaning I want to do something like unzip.

如果我运行 jar -xf filename。 jar 这会导致一些错误:

If I run jar -xf filename.jar this causes some error:

Exception in thread "main" java.io.IOException: Cannot run program "jar": 
java.io.IOException: error=2, No such file or directory
     at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
     at java.lang.Runtime.exec(Runtime.java:593)`


推荐答案

调整此示例:如何从JAR中提取Java资源和zip存档

或者尝试以下代码:


提取以编程方式的ZIP / JAR文件的内容



假设 jarFile 是要提取的jar / zip文件。 destDir 是提取它的路径:

Extract the Contents of ZIP/JAR Files Programmatically

Suppose jarFile is the jar/zip file to be extracted. destDir is the path where it will be extracted:

java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
    java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
    java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
    if (file.isDirectory()) { // if its a directory, create it
        f.mkdir();
        continue;
    }
    java.io.InputStream is = jar.getInputStream(file); // get the input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
    while (is.available() > 0) {  // write contents of 'is' to 'fos'
        fos.write(is.read());
    }
    fos.close();
    is.close();
}
jar.close();


来源 http://www.devx.com/tips/Tip/22124

这篇关于如何编写可以提取JAR文件并将其数据存储在指定目录(位置)的Java程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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