public static void loadLibraryFromJar ( String jarpath , String [ ] libs ) throws IOException { File libspath = File . createTempFile ( "libs" , "" ) ; if ( ! libspath . delete ( ) ) { throw new IOException ( "Cannot clean " + libspath ) ; } if ( ! libspath . exists ( ) ) { if ( ! libspath . mkdirs ( ) ) { throw new IOException ( "Cannot create directory " + libspath ) ; } } libspath . deleteOnExit ( ) ; try { addLibraryPath ( libspath . getAbsolutePath ( ) ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } for ( String lib : libs ) { String libfile = "lib" + lib + ".so" ; String path = jarpath + "/" + libfile ; if ( ! path . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "The path to be absolute (start with '/')." ) ; } File file = new File ( libspath , libfile ) ; file . createNewFile ( ) ; file . deleteOnExit ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int readBytes ; InputStream is = NativeUtils . class . getResourceAsStream ( path ) ; if ( is == null ) { throw new FileNotFoundException ( "File " + path + " was not found inside JAR." ) ; } OutputStream os = new FileOutputStream ( file ) ; try { while ( ( readBytes = is . read ( buffer ) ) != - 1 ) { os . write ( buffer , 0 , readBytes ) ; } } finally { os . close ( ) ; is . close ( ) ; } } for ( String lib : libs ) { System . loadLibrary ( lib ) ; } }
Loads library from current JAR archive