使用jna加載庫文件使用以下方式: Native.loadLibrary(dllName, className);java
loadLibrary源碼:eclipse
public static Object loadLibrary(String name, Class interfaceClass) {.net
return loadLibrary(name, interfaceClass, Collections.EMPTY_MAP);blog
}ip
即便用dll的名字加載庫文件,不能帶後綴。get
在不修改代碼代碼的前提下,那麼項目該如何適應dll文件路徑的動態變化呢,一方面可以在eclipse中正常運行,導出jar後能在生產環境執行。源碼
下面我寫了一個方法解決這個問題:it
public synchronized static Object loadDll(String libName, Class<?> className) {
String systemType = System.getProperty("os.name");
String libExtension = (systemType.toLowerCase().indexOf("win") != -1) ? ".dll"
: ".so";
String libFullName = libName + libExtension;
String nativeTempDir = System.getProperty("java.io.tmpdir");
InputStream in = null;
BufferedInputStream reader = null;
FileOutputStream writer = null;
File extractedLibFile = new File(nativeTempDir + File.separator
+ libFullName);
if (!extractedLibFile.exists()) {
try {
in = className.getResourceAsStream("/" + libFullName);
if (in == null)
in = className.getResourceAsStream(libFullName);
reader = new BufferedInputStream(in);
writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
while (reader.read(buffer) > 0) {
writer.write(buffer);
buffer = new byte[1024];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
if (writer != null)
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String dllName;
if (systemType.toLowerCase().indexOf("win") != -1) {
dllName = extractedLibFile.toString().replace(".dll", "");
} else {
dllName = extractedLibFile.toString().replace(".so", "");
}
return Native.loadLibrary(dllName, className);
}io
加載libHCEHomeCMS,調用例子:class
HCEHomeCMS INSTANCE = (HCEHomeCMS) PropertiesUtils.loadDll("libHCEHomeCMS",HCEHomeCMS.class);
到此,整個項目可使用動態方式加載dll,運行jar也能正常加載,有個問題須要注意下,32位dll文件須要使用32位jdk才能加載。
歡迎指出本文有誤的地方,轉載請註明原文出處https://my.oschina.net/7001/blog/672173