通过java的jar包实现依赖操作系统平台的功能时需要运用jni,依赖各平台生成的库,如dll,so等。在生成jar时一同打包这些库,其它项目直接引用此jar即可,而不需要把dll,so等库放到项目的某个目录或jdk目录。此方法需要jar有自解压功能,自解压实现如下:
public final class DongleNativeLibrary {
public static final String DONGLE_LIB_PREFIX = "dongle_native_libraries-";
private static final String JNI_LIB_NAME = "Dongle_java";
public static void load() {
if (!isLoaded() && !tryLoadLibrary()) {
String frameworkLibName = getVersionedLibraryName(System.mapLibraryName(JNI_LIB_NAME));
InputStream frameworkResource = DongleNativeLibrary.class.getResourceAsStream(frameworkLibName);
try {
File tempPath = createTemporaryDirectory();
tempPath.deleteOnExit();
String tempDirectory = tempPath.getCanonicalPath();
System.load(extractResource(frameworkResource, frameworkLibName, tempDirectory));
} catch (IOException e) {
throw new UnsatisfiedLinkError(String.format("Unable to extract native library into a temporary file (%s)", e.toString()));
}
}
}
private static boolean tryLoadLibrary() {
try {