【发布时间】:2015-11-30 15:49:08
【问题描述】:
我正在构建一个需要读取外部属性文件的 jar(使用 Maven 和 Spring Boot)。它应该在运行 jar 的同一目录中(或在它的相对路径中,如 ./config.properties 或 ./conf/config.properties。
现在我可以成功读取资源目录中的嵌入式 jar,但如果我尝试从本地目录读取它,InputStream 将是null。
我尝试将本地目录 . 添加到类路径中(解压 jar 我可以在 Class-Path 条目中看到它),但没有成功。
这是我尝试过的:
InputStream in = PropertiesLoader.class.getResourceAsStream("config.properties")
InputStream in = PropertiesLoader.class.getResourceAsStream("./config.properties")
InputStream in = PropertiesLoader.class.getClassLoader().getResourceAsStream("./config.properties")
InputStream in = PropertiesLoader.class.getClass().getResourceAsStream("./config.properties")
在我的 pom.xml 中,我有这个条目来将本地目录添加到类路径:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>bla.bla.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
我也尝试了user.dir 属性,但没有成功。
这应该很“简单”,但我很迷茫。
【问题讨论】:
-
cmiiw,您正在尝试使用您的 jar 从同一目录中读取文件,对吗?如果是,那我猜
new FileInputStream("./file_name.txt")应该足够了吧? -
你在 JAR 中使用
application.properties文件吗? JAR 之外的config.properties文件是否被覆盖? -
@kucing_terbang hm.. 我有一个 FileNotFound..
-
@geo 不,我没有使用 application.properties。应该是一个覆盖,但只是为了看看它是否会起作用,我已经将 jar 中的名称更改为“default.properties”。
标签: java maven jar spring-boot