[英]Read maven.properties file inside jar/war file
有没有办法用Java读取jar / war文件中的文件( maven.properties
)内容? 当不使用文件(在内存中)时,我需要从磁盘读取文件。 任何建议如何做到这一点?
问候,约翰·基斯
String path = "META-INF/maven/pom.properties";
Properties prop = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream(path );
try {
prop.load(in);
}
catch (Exception e) {
} finally {
try { in.close(); }
catch (Exception ex){}
}
System.out.println("maven properties " + prop);
首先要注意的是:从技术上讲,它不是文件。 JAR / WAR是一个文件,您正在寻找的是存档中的一个条目(又称为资源)。
而且由于它不是文件,因此您需要将其作为InputStream
如果JAR / WAR在类路径上,则可以执行SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties")
,其中SomeClass
是该JAR / WAR中的任何类
// these are equivalent: SomeClass.class.getResourceAsStream("/abc/def"); SomeClass.class.getClassLoader().getResourceAsStream("abc/def"); // note the missing slash in the second version
如果没有,您将必须像这样阅读JAR / WAR:
JarFile jarFile = new JarFile(file); InputStream inputStream = jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
现在,您可能想将InputStream
加载到Properties
对象中:
Properties props = new Properties();
// or: Properties props = System.getProperties();
props.load(inputStream);
或者,您可以将InputStream
读取为字符串。 如果您使用类似
String str = IOUtils.toString(inputStream)
String str = CharStreams.toString(new InputStreamReader(inputStream));
这绝对是可能的,尽管在不知道您的确切情况的情况下很难说清楚。
WAR和JAR文件基本上是.zip文件,因此,如果您具有包含.properties文件的文件的位置,则可以使用ZipFile将其打开并提取属性。
如果是JAR文件,则可能有一种更简单的方法:您可以将其添加到类路径中,然后使用类似以下方式加载属性:
SomeClass.class.getClassLoader().getResourceAsStream("maven.properties");
(假设属性文件在根包中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.