misschuer

常用链接

统计

积分与排名

百事通

最新评论

centos上运行jni

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.StringTokenizer;


public class Test {

    public static native void hello();
        static final String LIBFILENAME = "/home/my/java/libtest.so";

    static {
        //System.loadLibrary(LIBFILENAME);

        try {
            // 获取到java.library.path  及系统变量中Path中的内容
            String libpath = System.getProperty("java.library.path");
            if (libpath == null || libpath.length() == 0) {
                throw new RuntimeException("java.library.path is null");
            }
            //javaBinPath   jdk的bin目录D:\Program Files\Java\jdk1.6.0_11\bin
            String javaBinPath = null;
            StringTokenizer st = new StringTokenizer(libpath,
                    System.getProperty("path.separator"));
            if (st.hasMoreElements()) {
                javaBinPath = st.nextToken();
            } else {
                throw new RuntimeException("can not split library path:"
                        + libpath);
            }
            // 把dll文件写入到java.library.path中该dll放在ConvertWord2HM相同目录下,这个可以是你的类名
            InputStream inputStream = Test.class.getResourceAsStream(
                    LIBFILENAME);
            final File dllFile = new File(LIBFILENAME);
            if (!dllFile.exists()) {
                FileOutputStream outputStream = new FileOutputStream(dllFile);
                byte[] array = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(array)) != -1) {
                    outputStream.write(array, 0, bytesRead);
                }
                outputStream.flush();
                outputStream.close();
            }  
            // 动态加载dll
            System.load(dllFile.getPath());
            // 在虚拟机关闭的时候删除dll 这里看着用吧
            // dllFile.deleteOnExit();
        } catch (Throwable e) {
            throw new RuntimeException("load Convert.dll error!", e);
        }

    }
    public static void main(String[] args) {
        Test.hello();
    }
}


这个文件是在目录/home/my/java下的
javac Test.java
javah Test  //生成Test.h
然后自己写Test.cpp
.java .h .cpp 这些文件名字一定要一样
g++ -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -fPIC -shared -o libtest.so Test.cpp  // 转成你想要的文件 我这里是libtest.so 也可以是libtest.dll, 看你代码调用什么。
java Test 就可以运行了
用System.loadLibrary() 一直加载不了 只能网上找了个加载lib的代码

posted on 2015-05-07 17:14 此最相思 阅读(310) 评论(0)  编辑 收藏 引用 所属分类: Java


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理