如何从jar文件中提取zip文件

时间:2012-02-27 12:14:23

标签: java jar unzip

我的项目中有一个zip文件。当我通过IDE运行代码时,我的extract(String file, String destination)方法工作正常。

 D:/Tools/JAVA/Lodable_Creation/build/classes/ib2.zip-->
 String s1=getClass().getResource("Test.zip").getPath().toString();
  extract(s1, "c:\\");

这给了我路径s1 is--> D:\Tools\JAVA\Lodable_Creation\build

当我编译相同的代码并运行命令提示符

file:/D:/Tools/JAVA/Lodable_Creation/dist/Lodable_Creation.jar!/Test.zip
s1 is-->D:\Tools\JAVA\Lodable_Creation\dist

我没有得到输出。请帮帮我。

更新: -

public static void extract(String file, String destination) throws IOException {
    ZipInputStream in = null;
    OutputStream out = null;
    try {
      // Open the ZIP file
      in = new ZipInputStream(new FileInputStream(file));
      // Get the first entry
      ZipEntry entry = null;
      while ((entry = in.getNextEntry()) != null) {
        String outFilename = entry.getName();
        // Open the output file
        if (entry.isDirectory()) {
          new File(destination, outFilename).mkdirs();
        } else {
          out = new FileOutputStream(new File(destination,outFilename));
          // Transfer bytes from the ZIP file to the output file
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
          }
          out.close();
        }
      }
    } finally {
      // Close the stream
      if (in != null) {
        in.close();
      }
      if (out != null) {
        out.close();
      }
    }
  }

On Ok Click button

Map map = System.getenv();
 Set keys = map.keySet();
 String newString  = (String) map.get("CYGWIN_HOME");
 System.out.println(" " + newString);
 String  destination= newString.replace(";", "");
 System.out.println(" " + destination);
 String S =getClass().getResource("Test.zip").getPath().toString();
 File jarFile = new File(S);
 String file=jarFile.toString();
 extract(file,destination);

这是我的提取方法的实际代码和确定按钮。这是将Test.zip文件解压缩到Destination文件夹。即CYGWIN_HOME

1 个答案:

答案 0 :(得分:0)

如果您的文件路径实际上是一个网址(以"file://"开头),请使用new ZipInputStream((new URL(file)).openStream()),否则请像您一样使用new ZipInputStream(new FileInputStream(file))