我使用 Sparkjava 开发了一个简单的应用程序。我正在使用 Intellij,当我运行测试或在本地运行应用程序时,我的所有资源都是文件。
但是,当我部署时,整个过程作为 jar 文件运行。因此,我需要一种方法来从文件系统或 jar 中读取资源,具体取决于应用程序的启动方式。下面的代码可以完成工作,但看起来很笨拙:
String startedOffFile = new java.io.File(Main.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getName();
InputStream inputStream;
if(startedOffFile.endsWith(".jar")) {
ClassLoader cl = PropertiesParser.class.getClassLoader();
inputStream = cl.getResourceAsStream("myapp.dev.properties");
} else {
inputStream = new FileInputStream(filename);
}
有没有更干净/更简单的方法?
最佳答案
让您的 main
创建此类,以确定您的 java
可执行文件是否已定义 config.location 参数或将在类路径中查找。
java -Dconfig.location=/here/myapp.dev.properties -jar youapp.jar
public class ApplicationProperties {
public ApplicationProperties() throws IOException {
final Properties properties = new Properties();
String location = getProperty("config.location")
if(location != null) {
properties.load(new FileInputStream(getProperty("config.location", ENV_PROPERTIES_PATH)));
} else {
properties.load(Classname.class.getClassLoader().getResourceAsStream("myapp.dev.properties"));
}
}
public Properties getProperties() {
return properties;
}
}
关于java - 有没有更简单的方法来读取 *.jar 或文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805141/