2012-02-27 106 views
2

我在我的項目中有一個zip文件。當我通過IDE運行我的代碼時,我的extract(String file, String destination)方法正常工作。如何從jar文件中提取zip文件

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

這是我提取方法和OK按鈕實際代碼。這是將Test.zip文件解壓縮到目標文件夾。即CYGWIN_HOME

+0

我猜測「Test.zip」沒有找到,可能是因爲它不在你的類路徑中的正確位置。 – 2012-02-27 12:22:55

+0

雖然看起來更深我不知道有什麼作品。它似乎不像「Test.zip」上的getResource可以工作。我認爲你需要發佈你的真實代碼。 – 2012-02-27 12:29:03

+0

'extract()'的代碼是...? – 2012-02-27 12:30:12

回答

0

如果你的文件路徑其實是一個URL(與"file://"開始),然後使用new ZipInputStream((new URL(file)).openStream())以其它方式使用new ZipInputStream(new FileInputStream(file))像你已經做的。