
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JniLibrary {
static final String SEPARATOR;
static {
SEPARATOR = System.getProperty("file.separator");
}
private static boolean extract(String fileName, String mappedName) {
FileOutputStream os = null;
InputStream is = null;
File file = new File(fileName);
try {
if (file.exists()) {
file.delete();
}
is = JniLibrary.class.getResourceAsStream("/resources/" + mappedName);
if (is != null) {
int read;
byte[] buffer = new byte[4096];
os = new FileOutputStream(fileName);
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.close();
is.close();
return true;
}
} catch (Throwable e) {
try {
if (os != null)
os.close();
if (is != null)
is.close();
} catch (IOException e1) {
}
}
return false;
}
private static boolean load(String libName) {
try {
if (libName.indexOf(SEPARATOR) != -1) {
System.load(libName);
return true;
}
} catch (UnsatisfiedLinkError e) {
e.printStackTrace();
}
return false;
}
public static void extract(String name) {
String libName = name;
String path = System.getProperty("java.io.tmpdir");
if (path != null) {
path = path + "jni";
File file = new File(path);
path = file.getAbsolutePath();
if (!file.exists()) {
if (!file.mkdirs()) {
throw new UnsatisfiedLinkError("创建文件夹" + path + "失败");
}
}
String fileName = path + SEPARATOR + libName;
file = new File(fileName);
if (!file.exists()) {
extract(fileName, libName);
}
}
}
public static void loadLibrary(String name, String expdate) {
String libName = name;
String path = System.getProperty("java.io.tmpdir");
if (path != null) {
path = path + "jni";
File file = new File(path);
path = file.getAbsolutePath();
if (!file.exists()) {
if (!file.mkdirs()) {
throw new UnsatisfiedLinkError("创建文件夹" + path + "失败");
}
}
String fileName = path + SEPARATOR + libName;
file = new File(fileName);
Date date = new Date(file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String modifyDate = sdf.format(date);
if (!file.exists() || !modifyDate.equals(expdate)) {
if (extract(fileName, libName)) {
load(fileName);
return;
}
}
if (load(fileName))
return;
}
throw new UnsatisfiedLinkError("no " + libName + " in java.io.tmpdir or the jar file");
}
}
近期评论