将动态库打包在Jar包并调用的方法

来源:互联网 发布:如何编写app软件 编辑:程序博客网 时间:2024/06/05 20:51

       首先应该知道,无法直接加载Jar包中的动态库(dll、so)

       实现方法:使用输入输出流将动态库写在别的目录进行调用


<span style="font-size:18px;">     //getResourceAsStream以JAR中根路径为开始点    private synchronized static void loadLib(String libName) throws IOException {        String systemType = System.getProperty("os.name");        String libExtension = (systemType.toLowerCase().indexOf("win")!=-1) ? ".dll" : ".so";        String libFullName = libName + libExtension;        //动态库的输出目录 可自行设置        String nativeTempDir = System.getProperty("java.io.tmpdir");        InputStream in = null;        BufferedInputStream reader = null;        FileOutputStream writer = null;        File extractedLibFile = new File(nativeTempDir+File.separator+libFullName);        if(!extractedLibFile.exists()){            try {                // “/”代表Jar包的根目录                in = SecretKeyKeeper.class.getResourceAsStream("/" + libFullName);                if(in==null)                    in =  SecretKeyKeeper.class.getResourceAsStream(libFullName);                SecretKeyKeeper.class.getResource(libFullName);                reader = new BufferedInputStream(in);                writer = new FileOutputStream(extractedLibFile);                byte[] buffer = new byte[1024];                while (reader.read(buffer) > 0){                    writer.write(buffer);                    buffer = new byte[1024];                }            } catch (IOException e){                e.printStackTrace();            } finally {                if(in!=null)                    in.close();                if(writer!=null)                    writer.close();            }        }        System.load(extractedLibFile.toString());    }</span>

0 0
原创粉丝点击