Как извлечь ZIP-файл из файла JAR - PullRequest
2 голосов
/ 27 февраля 2012

У меня есть 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

И я не получаю вывод. Пожалуйста, помогите мне.

UPDATE: -

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);

Это мой действительный код для метода извлечения и для OK кнопки . Это распаковка файла Test.zip в целевую папку. т.е. CYGWIN_HOME

1 Ответ

0 голосов
/ 15 августа 2012

Если ваш путь к файлу на самом деле является URL (начинается с "file://"), тогда используйте new ZipInputStream((new URL(file)).openStream()), в противном случае используйте new ZipInputStream(new FileInputStream(file)), как вы уже делаете.

...