private static File extractLibraryFile ( String libFolderForCurrentOS , String libraryFileName , String targetFolder ) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName ; // Attach UUID to the native library file to ensure multiple class loaders can read the libsnappy-java multiple times. String uuid = UUID . randomUUID ( ) . toString ( ) ; String extractedLibFileName = String . format ( "snappy-%s-%s-%s" , getVersion ( ) , uuid , libraryFileName ) ; File extractedLibFile = new File ( targetFolder , extractedLibFileName ) ; try { // Extract a native library file into the target directory InputStream reader = null ; FileOutputStream writer = null ; try { reader = SnappyLoader . class . getResourceAsStream ( nativeLibraryFilePath ) ; try { writer = new FileOutputStream ( extractedLibFile ) ; byte [ ] buffer = new byte [ 8192 ] ; int bytesRead = 0 ; while ( ( bytesRead = reader . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , bytesRead ) ; } } finally { if ( writer != null ) { writer . close ( ) ; } } } finally { if ( reader != null ) { reader . close ( ) ; } // Delete the extracted lib file on JVM exit. extractedLibFile . deleteOnExit ( ) ; } // Set executable (x) flag to enable Java to load the native library boolean success = extractedLibFile . setReadable ( true ) && extractedLibFile . setWritable ( true , true ) && extractedLibFile . setExecutable ( true ) ; if ( ! success ) { // Setting file flag may fail, but in this case another error will be thrown in later phase } // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = null ; InputStream extractedLibIn = null ; try { nativeIn = SnappyLoader . class . getResourceAsStream ( nativeLibraryFilePath ) ; extractedLibIn = new FileInputStream ( extractedLibFile ) ; if ( ! contentsEquals ( nativeIn , extractedLibIn ) ) { throw new SnappyError ( SnappyErrorCode . FAILED_TO_LOAD_NATIVE_LIBRARY , String . format ( "Failed to write a native library file at %s" , extractedLibFile ) ) ; } } finally { if ( nativeIn != null ) { nativeIn . close ( ) ; } if ( extractedLibIn != null ) { extractedLibIn . close ( ) ; } } } return new File ( targetFolder , extractedLibFileName ) ; } catch ( IOException e ) { e . printStackTrace ( System . err ) ; return null ; } }
Extract the specified library file to the target folder