Path
始终为空,因为
jarFile.isFile() == false
:)
阿尔索
路径
它没用,因为你以后在外面看不懂
JarFile
,下面是一个如何阅读的例子
pom.xml
从当前的弹簧靴
uber
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(DemoApplication.class, args);
String currentJarPath = deduceCurrentJarPath();
Optional<InputStream> pom = findFileInJar(currentJarPath, "pom.xml");
if (pom.isPresent()) {
InputStream inputStream = pom.get();
byte[] pomBytes = new byte[1024 * 1024];
inputStream.read(pomBytes);
inputStream.close();
System.out.println(new String(pomBytes));
}
}
private static String deduceCurrentJarPath() {
String path = DemoApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
int endPathIndex = path.indexOf(".jar") + ".jar".length();
int startPathIndex = "file:".length();
return path.substring(startPathIndex, endPathIndex);
}
public static Optional<InputStream> findFileInJar(String jarPath, String fileName) {
try (JarFile jarFile = new JarFile(new File(jarPath))) {
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(fileName)) {
InputStream inputStream = jarFile.getInputStream(jarEntry);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return Optional.of(new ByteArrayInputStream(bytes));
}
}
return Optional.empty();
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
}