Search code examples
javanullpointerexceptiongeolocationresourcesclassloader

loading mmdb file using getClassLoader().getResource() returns null although the file exist in the resources


i have this piece of code :

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

and in my main class :

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

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

my goal is to load an mmdb file located in the resources in my project. when I run the main function, I catch an exception :

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

the file hierarchy in my project is as follow:

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

    -resources
        GeoLite2-Country.mmdb


I have tried to run the code with the absolute and relative path but did not work.

i am using IntelliJ

Is there any thing to do with it?


Solution

  • the thing that was missing is:

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

    in the pom.xml file