fbpx

Java Snippet Code - 自動依照 CPU 位元從 Jar 檔產生對應的 DLL 提供 JNI 使用

將 Jar 檔中的 Resource 複製到 library path 中,好讓不同位元的機器能夠載入正確的 Library。

以下為 Java 片段程式碼:

try {
    String libpath = System.getProperty("java.library.path");
    if (libpath == null || libpath.length() == 0) {
        throw new RuntimeException("not have java.library.path");
    }
    String path = null;
    StringTokenizer st = new StringTokenizer(libpath, System.getProperty("path.separator"));
    if (st.hasMoreElements()) {
        path = st.nextToken();
    } else {
        throw new RuntimeException("can not split library path:" + libpath);
    }

    // detect cpu arch
    String arch = System.getProperty("sun.arch.data.model");
    InputStream inputStream;
    if(arch.equals("32")){
        inputStream = Auth.class.getResource("lib32.so").openStream();
    }else{
        inputStream = Auth.class.getResource("lib64.so").openStream();
    }
    final File dllFile = new File(new File(path), "lib.so");
    if(!dllFile.exists()){
        libFile = dllFile.getAbsolutePath();
        if (!dllFile.exists()) {
            FileOutputStream outputStream = new FileOutputStream(dllFile);
            byte[] array = new byte[8192];
            for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
                outputStream.write(array, 0, i);
            }
            outputStream.close();
        }
    }
} catch (Throwable e) {
    throw new RuntimeException("load libjpam.so error!", e);
}

發佈留言