在windows平台,我们有时候会用到dll库来完成一些计算,我们一般是把dll编译好之后放在工程的lib目录下,然后工程->属性->JAVA Build Path下的native libaray location下选择lib目录就行了。如下图:
但是当我们达成jar包,就会提示找不到dll。怎么办呢?
总体方法是把jar包中的dll解压到一个缓存中,然后load。具体代码如下:
static {
try {
// getClass().getClassLoader().getResourceAsStream(arg0);
// System.out.println("MainTest.class.getClass()"+MainTest.class.getClass().toString());
InputStream in = MainTest.class
.getResourceAsStream("/lib/hello.dll");
System.out.println("MainTest.class.getClass()" + in);
File ffile = new File("");
String filePath = null;
filePath = ffile.getAbsolutePath() + File.separator
+ "hello.dll";
System.out.println("filePath hello.dll is " + filePath);
File dll = new File(filePath);
FileOutputStream out = new FileOutputStream(dll);
int i;
byte[] buf = new byte[1024];
try {
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} finally {
in.close();
out.close();
}
System.load(dll.getAbsolutePath());//
dll.deleteOnExit();
} catch (Exception e) {
System.err.println("load jni error!");
}
}