jar包内的文件不能通过绝对路径获取。经过查找资料我使用如下方式解决:
总结就是先获得jar包的绝对路径,然后得到所有的JarEntry(必须要加过滤条件,引用的jar包的文件也在这里面),
然后通过InputStream is = WriteUtil.class.getClassLoader().getResourceAsStream(jarEntry.getName());
获得文件输出流,从而处理。
注:尝试了很多种InputStream转为File的,URLURI转File的,都失败了。绕了圈子的原因是要在jar包内的文件夹循环处理文件,如果知道jar包内的文件名称和路径就简单的多了。
public static void buildAllTemplet(Table table,String path,String templetDir) {
if(ValidateUtil.projectIsJar()) {
buildAllTempletFromJar(table);
}else {
buildAllTempletFromDir(table, path, templetDir);
}
}
public static void buildAllTempletFromJar(Table table) {
List<JarEntry> list = getAllTempletJarEntry();
for (JarEntry jarEntry : list) {
buildTempletByEntry(table, jarEntry);
}
}
public static List<JarEntry> getAllTempletJarEntry(){
List<JarEntry> list = new ArrayList<JarEntry>();
try {
@SuppressWarnings("resource")
//获得jar包路径
JarFile jFile = new JarFile(System.getProperty("java.class.path"));
Enumeration<JarEntry> jarEntrys = jFile.entries();
while (jarEntrys.hasMoreElements()) {
JarEntry entry = jarEntrys.nextElement();
String name = entry.getName();
if(name.startsWith(InnerSettings.TEMPLET_DIR)) {
list.add(entry);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void buildTempletByEntry(Table table,JarEntry jarEntry) {
String jarEntryName = jarEntry.getName().replace(InnerSettings.TEMPLET_DIR, "");
String templetFileName = jarEntryName.substring(jarEntryName.lastIndexOf("/") + 1);
if(!jarEntry.isDirectory() && jarEntryName.endsWith(".templet") && !jarEntryName.startsWith("common")) {
String outName = InnerSettings.templetMap.get(templetFileName);
String newFileName = null;
if(outName == null) {
newFileName = table.getEntityName() + templetFileName.replace(".templet", ".out");
}else {
newFileName = CodeUtil.replaceTemplet(outName, table.getMap(), "table");
newFileName = CodeUtil.replaceTemplet(newFileName, CommonSettings.map, "common");
}
File outPath = new File(InnerSettings.OUT_DIR + table.getTableName() + jarEntryName.replace(templetFileName, newFileName));
outPath.getParentFile().mkdirs();
InputStream is = WriteUtil.class.getClassLoader().getResourceAsStream(jarEntry.getName());
writeFileByTemplet(is, outPath, table);
System.out.println("生成: " + jarEntryName.replace(templetFileName, newFileName));
}
}