您的位置:首页 > 编程语言 > Java开发

springboot动态加载native类库

2017-07-05 00:00 696 查看
##序
有些时候需要使用到本地类库来实现一些功能,比如在linux下使用jni去访问so库文件,这个时候就需要涉及库文件的加载。本文介绍一下如何动态加载库文件,即把库文件放到工程项目里头,方便工程的可移植性,然后在运行时去加载。

##动态加载

public class LibLoader {
public static void loadLib(String libName) {
String resourcePath = "/" + libName;
String folderName = System.getProperty("java.io.tmpdir") + "/lib/";
File folder = new File(folderName);
folder.mkdirs();
File libFile = new File(folder, libName);
if (libFile.exists()) {
System.load(libFile.getAbsolutePath());
} else {
try {
InputStream in = LibLoader.class.getResourceAsStream(resourcePath);
FileUtils.copyInputStreamToFile(in,libFile);
in.close();
System.load(libFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to load required lib", e);
}
}
}
}


将so文件放在工程的resources目录下

##使用

public class DemoJniClient{
public native int helloWorld(String arg);
static {
LibLoader.loadLib("demo.so");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring Boot