有些时候需要使用到本地类库来实现一些功能,比如在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");}}
