Java在jar包中加载so包dll包dylib等

背景

使用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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值