前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java:加载jar包中的动态库

java:加载jar包中的动态库

作者头像
10km
发布2019-05-25 20:29:23
3.6K0
发布2019-05-25 20:29:23
举报
文章被收录于专栏:10km的专栏10km的专栏

java中System.load(String)方法可以加载一个动态库,有时为了便于管理和发行,我们会把动态库打包jar包一起发行。这时如何加载jar包中的动态库呢? 原理也很简单,就是先把动态库解压到系统临时文件夹,再调用System.load(String)方法加载动态库,github上这个项目native-utils上提供了完整实现代码,我做了一些简化,实现如下:

代码语言:javascript
复制
package net.gdface.cassdk;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * A simple library class which helps with loading dynamic libraries stored in the
 * JAR archive. These libraries usually contain implementation of some methods in
 * native code (using JNI - Java Native Interface).
 * 
 * @see <a href="http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar">http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar</a>
 * @see <a href="https://github.com/adamheinrich/native-utils">https://github.com/adamheinrich/native-utils</a>
 *
 */
public class NativeUtils {
 
    /**
     * The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
     */
    private static final int MIN_PREFIX_LENGTH = 3;
    public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils";

    /**
     * Temporary directory which will contain the DLLs.
     */
    private static File temporaryDir;

    /**
     * Private constructor - this class will never be instanced
     */
    private NativeUtils() {
    }

    /**
     * 从jar包中加载动态库
     * 先将jar包中的动态库复制到系统临时文件夹,然后加载动态库,并且在JVM退出时自动删除。
     * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after
     * exiting.
     * Method uses String as filename because the pathname is "abstract", not system-dependent.
     * 
     * @param path 要加载动态库的路径,必须以'/'开始,比如 /lib/mylib.so,必须以'/'开始
     * @param loadClass 用于提供{@link ClassLoader}加载动态库的类,如果为null,则使用NativeUtils.class
     * @throws IOException 动态库读写错误
     * @throws FileNotFoundException 没有在jar包中找到指定的文件
     */
    public static synchronized void loadLibraryFromJar(String path, Class<?> loadClass) throws IOException {
 
        if (null == path || !path.startsWith("/")) {
            throw new IllegalArgumentException("The path has to be absolute (start with '/').");
        }
 
        // Obtain filename from path
        String[] parts = path.split("/");
        String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
 
        // Check if the filename is okay
        if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
            throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
        }
 
        // 创建临时文件夹
        if (temporaryDir == null) {
            temporaryDir = createTempDirectory(NATIVE_FOLDER_PATH_PREFIX);
            temporaryDir.deleteOnExit();
        }
		// 临时文件夹下的动态库名
        File temp = new File(temporaryDir, filename);
        Class<?> clazz = loadClass == null ? NativeUtils.class	: loadClass;
        // 从jar包中复制文件到系统临时文件夹
        try (InputStream is = clazz.getResourceAsStream(path)) {
            Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            temp.delete();
            throw e;
        } catch (NullPointerException e) {
            temp.delete();
            throw new FileNotFoundException("File " + path + " was not found inside JAR.");
        }
		// 加载临时文件夹中的动态库
        try {
            System.load(temp.getAbsolutePath());
        } finally {
        	// 设置在JVM结束时删除临时文件
        	temp.deleteOnExit();
        }
    }
	/**
	 * 在系统临时文件夹下创建临时文件夹
	 */
    private static File createTempDirectory(String prefix) throws IOException {
        String tempDir = System.getProperty("java.io.tmpdir");
        File generatedDir = new File(tempDir, prefix + System.nanoTime());
        
        if (!generatedDir.mkdir())
            throw new IOException("Failed to create temp directory " + generatedDir.getName());
        
        return generatedDir;
    }
}

持续改进代码gitee仓库位置

https://gitee.com/l0km/common-java/blob/master/common-base/src/main/java/net/gdface/utils/NativeUtils.java

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年02月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 持续改进代码gitee仓库位置
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档