我正在構建一個依賴於某些配置文件的命令行工具。我該如何選擇maven項目中配置文件的位置
在開發過程中,我將這些文件放在src/main/resources
之下,並且可以通過getClass().getResourceAsStream("/config-file-name")
訪問,效果很好。
我選擇maven-assembly-plugin來構建具有所有依賴項的jar。
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.myproject.Scheduler</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-my-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
配置文件都包裝在jar中,但我想分開它們。
所以,我添加了以下配置,
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>conf.properties</include>
</includes>
<filtering>true</filtering>
<excludes>
<exclude></exclude>
</excludes>
<targetPath>..</targetPath>
</resource>
</resources>
做到了這一點之後,配置文件是沿側罐子,而不是包裹在罐子。
但我的代碼現在無法訪問這些文件。
我是否需要改變訪問代碼中文件的方式?
或者我應該不需要把這些文件放在src/main/resources/
,任何替代?
如果有人知道,請幫助。
謝謝。
更新:最後,我放棄了使用maven資源文件,而不是,我默認設置的文件路徑相同的路徑罐子,一切正常,除了Eclipse的抱怨。
由於我想將配置文件從jar中移出,並且不希望它位於target/classes文件夾中,所以我使用<targetPath>..</targetPath>
將配置文件移動到與jar文件相同的目錄中。
當我重新生成eclipse項目設置時,Eclipse說:無法在輸出文件夾「project/target」中嵌套輸出文件夾「project/target/test-classes」。
有人幫我嗎?
配置文件在你的類路徑中的位置? 'getClass()。getResourceAsStream(「/ config-file-name」)'使用類路徑位置來查找資源。 – 2012-03-08 07:30:12
是的,它使用,但它是訪問maven項目中的資源文件的正常方式。我想我可能會把我的配置文件放在其他地方而不是src/main/resources,我更喜歡與正在運行的jar相同的目錄,我正在尋找如何在代碼內部運行jar路徑。 – 2012-03-08 07:49:01
'System.getProperty(「user.dir」)'會給你內部代碼的路徑。請參閱[System.getProperties()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29)和[System.getProperty(String key) ](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperty%28java.lang.String%29)。 – FrVaBe 2012-03-08 08:05:55