【问题标题】:loading mmdb file using getClassLoader().getResource() returns null although the file exist in the resources使用 getClassLoader().getResource() 加载 mmdb 文件会返回 null,尽管该文件存在于资源中
【发布时间】:2020-12-08 23:12:22
【问题描述】:

我有这段代码:

class GeoLocator{
    public GeoLocator() throws IOException {
            final URL url = getClass().getClassLoader().getResource("GeoLite2-Country.mmdb");
            if (url == null) {
                throw new IOException("File not found!");
            }
    }
}

在我的主要课程中:

public class Main {
    public static void main(String[] args) {

        try {
            GeoLocator geoLocator = new GeoLocator();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我的目标是加载位于我项目资源中的 mmdb 文件。 当我运行 main 函数时,我捕获了一个异常:

java.io.IOException: File not found!
    at com.a.GeoLocator.<init>(GeoLocator.java:19)
    at com.a.Main.main(Main.java:11)

我的项目中的文件层次结构如下:

-main
    -java
        -com.a
            GeoLocator.java
            Main.java

    -resources
        GeoLite2-Country.mmdb


我尝试过使用绝对路径和相对路径运行代码,但没有成功。

我正在使用 IntelliJ

有什么关系吗?

【问题讨论】:

  • 您可能需要将resourses 重命名为resources,这是Maven 期望在默认情况下查找资源的位置。
  • 其实它被命名为resources 只是在帖子中写错了。我会在这里修正那个错字。

标签: java nullpointerexception geolocation resources classloader


【解决方案1】:

缺少的是:

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/GeoLite2-Country.mmdb</include>
                    <include>**/apache.log</include>
                </includes>
            </resource>
        </resources>

在 pom.xml 文件中

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2017-08-12
    • 2012-01-17
    • 2012-04-12
    • 2021-01-09
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多