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 {
// 獲取到j(luò)ava.library.path 及系統(tǒng)變量中Path中的內(nèi)容
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文件寫入到j(luò)ava.library.path中該dll放在ConvertWord2HM相同目錄下,這個(gè)可以是你的類名
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();
}
// 動(dòng)態(tài)加載dll System.load(dllFile.getPath());
// 在虛擬機(jī)關(guān)閉的時(shí)候刪除dll 這里看著用吧
// dllFile.deleteOnExit();
}
catch (Throwable e) {
throw new RuntimeException("load Convert.dll error!", e);
}
}
public static void main(String[] args) {
Test.hello();
}
}
這個(gè)文件是在目錄/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 // 轉(zhuǎn)成你想要的文件 我這里是libtest.so 也可以是libtest.dll, 看你代碼調(diào)用什么。
java Test 就可以運(yùn)行了
用System.loadLibrary() 一直加載不了 只能網(wǎng)上找了個(gè)加載lib的代碼