背景
使用IDE为idea,/lib/libxyz.so位于resource下,通过动态设置jar路径,然后加载。
System.loadLibrary("xyz");
如果直接启动idea系统正常加载。但将项打包为jar,启动jar包运行确出现找不到jar加载异常,产生unsatisfied linked error
异常。
分析
通过idea启动项目,XXX.class.getResource(“/lib/libxyz.so”).getPath()获取的路径如下
/Users/xxx/target/classes/lib/libxyz.so
而loadLibrary最终是通过native方法来载入的。
当将项目打成jar包,然后运行XXX.class.getResource(“/lib/libxyz.so”).getPath()输出路径如下
/Users/xxx/target/yyy-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/lib/libxyz.so
最终native方法在文件系统中无法找到最后的jar包里的so包。
解决
由于XXXDecoder.class.getResourceAsStream(sourcePath);方法可以获取InputStream输入流,因此将so包中的文件拷贝到指定的目录下[1],然后通过native可访问的路径去加载即可。下面的代码将文件拷贝到系统当前目录下,然后返回路径。
public static String loadlib(String fileName,String sourcePath) throws IOException {
InputStream in = CtripDecoder.class.getResourceAsStream(sourcePath);
byte[] buffer = new byte[1024];
File temp = new File(fileName);
FileOutputStream fos = new FileOutputStream(temp);
int read = -1;
while((read = in.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fos.close();
in.close();
String abPath = temp.getAbsolutePath();
return abPath.substring(0,abPath.lastIndexOf("/"));
}
参考
[1] Load library from jar,
https://stackoverflow.com/questions/4113317/load-library-from-jar