读取jar/war文件中的maven.properties文件 [英] Read maven.properties file inside jar/war file
问题描述
是否可以使用Java读取jar/war文件中文件(maven.properties
)的内容?当不使用文件时(在内存中),我需要从磁盘读取文件.有关如何执行此操作的任何建议?
Is there a way to read the content of a file (maven.properties
) inside a jar/war file with Java? I need to read the file from disk, when it's not used (in memory). Any advise on how to do this?
关于, 约翰·基斯(Johan-Kees)
Regards, Johan-Kees
推荐答案
首先要解决的问题:从技术上讲,它不是文件. JAR/WAR是一个文件,您正在寻找的是归档文件中的一个条目(又称为资源).
One thing first: technically, it's not a file. The JAR / WAR is a file, what you are looking for is an entry within an archive (AKA a resource).
由于它不是文件,因此您需要将其作为InputStream
And because it's not a file, you will need to get it as an InputStream
-
如果JAR/WAR位于 classpath,您可以执行
SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties")
,其中SomeClass
是JAR/WAR中的任何类
If the JAR / WAR is on the classpath, you can do
SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties")
, whereSomeClass
is any class inside that 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:
If not, you will have to read the JAR / WAR like this:
JarFile jarFile = new JarFile(file);
InputStream inputStream =
jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
现在您可能想将InputStream
加载到Properties
对象中
Now you probably want to load the InputStream
into a Properties
object:
Properties props = new Properties();
// or: Properties props = System.getProperties();
props.load(inputStream);
或者您可以将InputStream
读取为字符串.如果您使用类似
Or you can read the InputStream
to a String. This is much easier if you use a library like
String str = IOUtils.toString(inputStream)
String str = CharStreams.toString(new InputStreamReader(inputStream));
这篇关于读取jar/war文件中的maven.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!