借鉴:https://blog.csdn.net/paullinjie/article/details/53189004
URL url = this.getClass().getClassLoader().getResource(“mapper”);
String jarstr = url.toString();
//截取jar包路径 // : jarpath=:jar:file:/E:/workplace/erupt/target
// /erupt-0.0.1-SNAPSHOT.jar!/
String jarpath = jarstr.substring(0, jarstr.indexOf("!/")+2);
log.info(“jarpath=:{}”,jarpath);
ConcurrentHashMap<String,byte[]> map = new ConcurrentHashMap<> ();
try {
url = new URL(jarpath);
JarURLConnection con = (JarURLConnection) url.openConnection();
//获取jar包文件
JarFile jarFile = con.getJarFile();
//获取jar 报下的所有文件枚举
Enumeration entries = jarFile.entries();
for (; entries.hasMoreElements(); ){
//异步线程执行过滤需要的文件
CompletableFuture.runAsync(() -> {
try {
getKey(map, entries);
} catch (IOException e) {
e.printStackTrace();
}
});
}
} catch (IOException e) {
log.info(“jarpath=:{}”,jarpath);
}
Thread.sleep(5000);
for (Map.Entry < String, byte [] > entry : map.entrySet()) {
log.info(“key={},value={}”,entry.getKey(), entry.getValue());
}
}
private void getKey(Map<String, byte[]> map, Enumeration<JarEntry> entries) throws IOException {
JarEntry jarEntry = entries.nextElement();
//获取文件路径
String name = jarEntry.getName();
//过滤需要文件的名称
if(name.endsWith("puk") || name.endsWith("pvk")){
String keyName = name.substring(name.lastIndexOf("/") + 1);
//加载到流里读取
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(name);
byte [] bytes = new byte [inStream.available()];
byte [] buffer = new byte [2048];
int read ;
for (int offset = 0 ; (read=inStream.read(buffer,0,buffer.length))!=-1; offset+=read) {
System.arraycopy(buffer,0, bytes,offset,read);
}
map.put(keyName,bytes);
}
}