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

查看:16
本文介绍了如何编写可以提取 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 和 zip 存档中提取 Java 资源

或者试试这个代码:

假设 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天全站免登陆