使用getclassloader()加载mmdb文件getresource()返回null,尽管该文件存在于资源中

6ojccjat  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(662)

我有一段代码:

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
有什么关系吗?

oogrdqng

oogrdqng1#

缺少的是:

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

在pom.xml文件中

相关问题