Skip to content

Commit b4ce0fc

Browse files
author
quding
committed
jni加载类库工具类
1 parent 74b4260 commit b4ce0fc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package cn.mrdear.util.jniUtil;
2+
3+
import java.io.*;
4+
5+
/**
6+
* Contains helper methods for loading native libraries, particularly JNI.
7+
*
8+
* @author gkubisa
9+
*/
10+
public class NativeLibraryLoader {
11+
/**
12+
* Utility classes should not have a public constructor.
13+
*/
14+
private NativeLibraryLoader() { }
15+
16+
/**
17+
* Loads a native shared library. It tries the standard System.loadLibrary
18+
* method first and if it fails, it looks for the library in the current
19+
* class path. It will handle libraries packed within jar files, too.
20+
*
21+
* @param libraryName - name of the library to load
22+
* @throws IOException if the library cannot be extracted from a jar file
23+
* into a temporary file
24+
*/
25+
public static void loadLibrary(String libraryName) throws IOException {
26+
try {
27+
System.loadLibrary(libraryName);
28+
} catch (UnsatisfiedLinkError e) {
29+
String fileName = System.mapLibraryName(libraryName);
30+
31+
int dotPosition = fileName.lastIndexOf('.');
32+
File file = File.createTempFile(fileName.substring(0, dotPosition), fileName.substring(dotPosition));
33+
file.deleteOnExit();
34+
35+
byte[] buffer = new byte[4096];
36+
InputStream inputStream = NativeLibraryLoader.class.getClassLoader().getResourceAsStream(fileName);
37+
OutputStream outputStream = new FileOutputStream(file);
38+
39+
try {
40+
while ( inputStream.available() > 0 ) {
41+
int StreamLength = inputStream.read(buffer);
42+
if ( StreamLength >= 0 ) {
43+
outputStream.write(buffer, 0, StreamLength);
44+
}
45+
}
46+
} finally {
47+
outputStream.close();
48+
inputStream.close();
49+
}
50+
51+
System.load(file.getAbsolutePath());
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)