private static File extract ( File file , File directory ) throws IOException { if ( file == null ) throw new IllegalArgumentException ( "File is null" ) ; if ( directory == null ) throw new IllegalArgumentException ( "Directory is null" ) ; File target = new File ( directory , file . getName ( ) ) ; if ( target . exists ( ) ) recursiveDelete ( target ) ; if ( ! target . mkdirs ( ) ) throw new IOException ( "Could not create " + target ) ; JarFile jar = null ; try { jar = new JarFile ( file ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry je = entries . nextElement ( ) ; File copy = new File ( target , je . getName ( ) ) ; if ( ! je . isDirectory ( ) ) { InputStream in = null ; OutputStream out = null ; // Make sure that the directory is _really_ there if ( copy . getParentFile ( ) != null && ! copy . getParentFile ( ) . exists ( ) ) { if ( ! copy . getParentFile ( ) . mkdirs ( ) ) throw new IOException ( "Could not create " + copy . getParentFile ( ) ) ; } try { in = new BufferedInputStream ( jar . getInputStream ( je ) ) ; out = new BufferedOutputStream ( new FileOutputStream ( copy ) ) ; byte [ ] buffer = new byte [ 4096 ] ; for ( ; ; ) { int nBytes = in . read ( buffer ) ; if ( nBytes <= 0 ) break ; out . write ( buffer , 0 , nBytes ) ; } out . flush ( ) ; } finally { try { if ( out != null ) out . close ( ) ; } catch ( IOException ignore ) { // Ignore } try { if ( in != null ) in . close ( ) ; } catch ( IOException ignore ) { // Ignore } } } else { if ( ! copy . exists ( ) ) { if ( ! copy . mkdirs ( ) ) throw new IOException ( "Could not create " + copy ) ; } else { if ( ! copy . isDirectory ( ) ) throw new IOException ( copy + " isn't a directory" ) ; } } } } finally { try { if ( jar != null ) jar . close ( ) ; } catch ( IOException ignore ) { // Ignore } } return target ; }
Extract a JAR type file