【问题标题】:Take configuration file out of jar and access it?从jar中取出配置文件并访问它?
【发布时间】:2014-04-04 17:23:16
【问题描述】:

我有两个项目 - foo 和 bar。 Foo 是主要项目,它依赖于 bar 项目。 Foo 也是保存配置文件 (conf.xml) 的项目。这些项目被打包为单独的 jar。 conf.xml 包含在 foo.jar 中,主类访问它是这样的:

MyApp.class.getClassLoader().getResource("conf.xml");

要运行这些,我在命令行上输入:

java -cp "*" com.example.MyApp

一切正常。

我的问题是,有时我想在不重建项目的情况下更改 conf.xml。所以我想把 conf.xml 从罐子里拿出来,这样我就可以自己编辑了。那么问题是jar里面的类再也找不到conf.xml了。可以在不更改我的类中的代码的情况下解决此问题吗?

【问题讨论】:

标签: java


【解决方案1】:

您有多种选择。

你可以提取配置文件,编辑它并放回去:

# extract conf.xml from the jar
jar xf path/to.jar conf.xml

# edit the extracted conf.xml with your favorite editor
# ...

# put conf.xml back
jar uf path/to.jar conf.xml

或者不放回去,可以保留在目录中,不加回jar,将容器目录加到classpath中,放在jar之前:

java -cp .:path/to.jar com.example.MyApp

【讨论】:

    【解决方案2】:

    两个指针:

    1. 你的 conf 文件所在的目录应该在类路径中
    2. 尝试使用 MyApp.class.getClassLoader().getResource("/conf.xml");

    注意“/”,它告诉 java 将其定位在类路径的根目录中。我假设该文件位于您运行程序的同一目录中。

    【讨论】:

    • 或者你也可以试试:MyApp.class.getResourceAsStream
    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2015-11-30
    • 1970-01-01
    • 2017-09-05
    • 2013-01-02
    相关资源
    最近更新 更多