Skip to content

Instantly share code, notes, and snippets.

@amcclosky
Created June 26, 2012 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcclosky/2997867 to your computer and use it in GitHub Desktop.
Save amcclosky/2997867 to your computer and use it in GitHub Desktop.
Dynamic loading of Native code embedded in a jar
<copy file="src/com/amcclosky/nativelib/libJNINativeLibrary.so" todir="bin/com/amcclosky/nativelib"/>
package com.amcclosky.nativelib;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NativeLibrary {
public static final long NULL = 0;
protected static final Logger log = Logger.getLogger(Peer.class.getPackage().getName());
static {
if(System.getProperty("os.name").compareTo("Linux") != 0) {
System.loadLibrary("JNINativeLibrary");
} else {
NativeLibrary.loadLinuxLibrary();
}
}
/**
* Copy a resorce to a file.
*
* @param clss
* @param resource
* @param toFile
* @throws IOException
*/
public static void copyResourceToFile(Class clss, String resource, File toFile) throws IOException {
InputStream input = clss.getResourceAsStream(resource);
if (input == null)
throw new IllegalArgumentException("Could not get resource " + resource + " from class " + clss.getName());
else {
OutputStream output = null;
IOException ioe = null;
try {
output = new FileOutputStream(toFile);
byte b[] = new byte[10 * 1024];
int n;
while ((n = input.read(b)) > 0)
output.write(b, 0, n);
} catch (IOException e) {
ioe = e;
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
ioe = e;
}
if (output != null)
try {
output.close();
} catch (IOException e) {
ioe = e;
}
if (ioe != null)
throw ioe;
}
}
}
public static void loadLinuxLibrary() {
File nativeLib = new File( System.getProperty("user.home") + "/.nativelibrary/" + "libJNINativeLibrary.so");
if(!nativeLib.exists()) {
try {
NativeLibrary.copyResourceToFile(NativeLibrary.class, "libJNINativeLibrary.so", nativeLib);
} catch (IOException e) {
log.log(Level.SEVERE, "Unable to load native library.", e);
}
}
System.load(nativeLib.getAbsolutePath());
}
/* JNI method stubbs go here. */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment