【问题标题】:How to add an external folder to the class path?如何将外部文件夹添加到类路径?
【发布时间】:2015-04-02 01:35:29
【问题描述】:

所以我有以下文件夹结构:

  • 项目
    • 库 (从此文件夹运行 jar)
    • properties(要加载的属性文件在此文件夹中)

我正在尝试通过 X.class.getClassLoader().getResource("properties/fileName") 加载属性文件。此方法在 eclipse 中有效,但是当我使用 maven 构建 jar 时,它无法找到该文件,给出一个文件未找到异常。

我怀疑该文件夹不在类路径中,因为如果我运行 getClassLoader().getResources("") 属性文件夹永远不会出现。我尝试了之前关于stackoverflow的问题中的所有建议,但到目前为止都没有奏效。

我也试过运行 java -cp 和 -classpath 但还是失败了。

【问题讨论】:

    标签: java maven


    【解决方案1】:

    使用 Maven 时,*.properties 等文件和任何其他不可编译的文件必须默认位于 src/main/resources 文件夹中才能使用。

    此外,我建议您使用Thread.currentThread().getContextClassLoader() 来获取适当的类加载器,以便加载资源。

    无论如何,如果您想在类路径中拥有自定义文件夹,我建议您在 pom.xml 处添加为资源,如下所示:

    <project>
        ...
        <build>
            ...
            <resources>
                <resource>
                    <!-- The folder you want to be a resource (from project root folder), like: project/properties -->
                    <directory>properties</directory>
                    <!-- Filtering if Maven should post-process text files to find and replace ${key} params: in most cases, leave it false -->
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    </project>
    

    【讨论】:

    • 当我尝试你的建议时,getClassLoader().getResources("") 找到一个 URL,但是当它被传递到 FileInputStream 构造函数时,我得到一个找不到文件的异常。我希望我可以使用 Thread.currentThread().getContextClassLoader() 但我被遗留代码困住了......
    • 我认为您的类加载器没有看到该文件。有没有办法改变类加载器?它可以为您解决这个问题...无论如何,我会花一些时间检查解决方法。
    • 类加载器永远不会看到该文件,因为无论我做什么,它都不在类路径上。我希望我可以更改类加载器,但我不能。我做了一个工作,我不再使用类加载器,所以它现在是“固定的”。感谢您的帮助,无需浪费您的时间。
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 2016-07-10
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多