2012-05-07 59 views
2

我想從當前運行的jar中提取2個jar文件,但是它們總是以2kb結尾,即使它們的大小是104kb和1.7m,所以我得到了從當前運行的jar中提取一個jar

public static boolean extractFromJar(String fileName, String dest) { 
    if (Configuration.getRunningJarPath() == null) { 
     return false; 
    } 
    File file = new File(dest + fileName); 
    if (file.exists()) { 
     return false; 
    } 

    if (file.isDirectory()) { 
     file.mkdir(); 
     return false; 
    } 
    try { 
     JarFile jar = new JarFile(Configuration.getRunningJarPath()); 
     Enumeration<JarEntry> e = jar.entries(); 
     while (e.hasMoreElements()) { 
      JarEntry je = e.nextElement(); 
      InputStream in = new BufferedInputStream(jar.getInputStream(je)); 
      OutputStream out = new BufferedOutputStream(
        new FileOutputStream(file)); 
      copyInputStream(in, out); 
     } 
     return true; 
    } catch (Exception e) { 
     Methods.debug(e); 
     return false; 
    } 
} 

private final static void copyInputStream(InputStream in, OutputStream out) 
     throws IOException { 
    while (in.available() > 0) { 
     out.write(in.read()); 
    } 
    out.flush(); 
    out.close(); 
    in.close(); 
} 

回答

2

這應該更好地工作,然後依靠InputStream.available()方法:

private final static void copyInputStream(InputStream in, OutputStream out) 
     throws IOException { 
    byte[] buff = new byte[4096]; 
    int n; 
    while ((n = in.read(buff)) > 0) { 
     out.write(buff, 0, n); 
    } 
    out.flush(); 
    out.close(); 
    in.close(); 
} 
1

available()方法是不可靠的讀取數據,因爲它只是一個估計,根據其文件。
您需要依賴read()方法直到讀取非-ve。

byte[] contentBytes = new byte[ 4096 ]; 
int bytesRead = -1; 
while ((bytesRead = inputStream.read(contentBytes)) > 0) 
{ 
    out.write(contentBytes, 0, bytesRead); 
} // while available 

你可以通過一個討論如何處理available()的問題是在here