这是我用来加载dll
或so
捆绑在 jar 中的库的一些代码。
库必须作为资源添加。我们使用 maven 并将它们放在这个层次结构中:
src/main/resources/lib/win-x86/<dlls for 32-bit windows>
src/main/resources/lib/linux-x86/<so for 32-bit linux>
src/main/resources/lib/linux-x86_64/<so for 64-bit linux>
src/main/resources/lib/linux-ia64/<so for 64-bit linux on itanium>
共享库将被解压到平台的 tmp 目录,并且在解压时也有一个临时名称。这是为了让多个进程加载 dll/so 而不共享实际提取的 dll/so,因为如果具有相同的名称,解包可能会覆盖现有的(在替换文件时在某些平台上会出现非常奇怪的行为)。
该文件也设置为已deleteOnExit
设置,但在 Windows AFAIK 上不起作用。
NativeLoader.java
public class NativeLoader {
public static final Logger LOG = Logger.getLogger(NativeLoader.class);
public NativeLoader() {
}
public void loadLibrary(String library) {
try {
System.load(saveLibrary(library));
} catch (IOException e) {
LOG.warn("Could not find library " + library +
" as resource, trying fallback lookup through System.loadLibrary");
System.loadLibrary(library);
}
}
private String getOSSpecificLibraryName(String library, boolean includePath) {
String osArch = System.getProperty("os.arch");
String osName = System.getProperty("os.name").toLowerCase();
String name;
String path;
if (osName.startsWith("win")) {
if (osArch.equalsIgnoreCase("x86")) {
name = library + ".dll";
path = "win-x86/";
} else {
throw new UnsupportedOperationException("Platform " + osName + ":" + osArch + " not supported");
}
} else if (osName.startsWith("linux")) {
if (osArch.equalsIgnoreCase("amd64")) {
name = "lib" + library + ".so";
path = "linux-x86_64/";
} else if (osArch.equalsIgnoreCase("ia64")) {
name = "lib" + library + ".so";
path = "linux-ia64/";
} else if (osArch.equalsIgnoreCase("i386")) {
name = "lib" + library + ".so";
path = "linux-x86/";
} else {
throw new UnsupportedOperationException("Platform " + osName + ":" + osArch + " not supported");
}
} else {
throw new UnsupportedOperationException("Platform " + osName + ":" + osArch + " not supported");
}
return includePath ? path + name : name;
}
private String saveLibrary(String library) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
String libraryName = getOSSpecificLibraryName(library, true);
in = this.getClass().getClassLoader().getResourceAsStream("lib/" + libraryName);
String tmpDirName = System.getProperty("java.io.tmpdir");
File tmpDir = new File(tmpDirName);
if (!tmpDir.exists()) {
tmpDir.mkdir();
}
File file = File.createTempFile(library + "-", ".tmp", tmpDir);
// Clean up the file when exiting
file.deleteOnExit();
out = new FileOutputStream(file);
int cnt;
byte buf[] = new byte[16 * 1024];
// copy until done.
while ((cnt = in.read(buf)) >= 1) {
out.write(buf, 0, cnt);
}
LOG.info("Saved libfile: " + file.getAbsoluteFile());
return file.getAbsolutePath();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ignore) {
}
}
}
}
}
这些库是通过创建一个实例来加载的NativeLoader
,然后在loadLibrary("thelibrary")
没有特定于操作系统的前缀和扩展的情况下调用。
这对我们来说效果很好,但您必须手动将共享库添加到不同的资源目录,然后构建 jar。
我意识到这个类中的一些代码可能很奇怪或过时,但请记住这是我几年前编写的代码,它运行得非常好。