javafilegeoip2

Java geoip2 java.io.FileNotFoundException:


I use geoip2 to determine the country by ip. During development and testing of the code, I have no problems, but when I run the compiled archive, I encounter a java.io.FileNotFoundException exception. I understand that this is because the path to the file is absolute, and in the archive it changes. Question: How do I need to change my code so that even from the archive I can access the file?

   public static String getCountryByIp(String ip) throws Exception {
    File database = new File(URLDecoder.decode(GeoUtils.class.getResource("/GeoLite2-Country.mmdb").getFile(),"UTF-8"));


    DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
    InetAddress ipAddress = InetAddress.getByName(ip);
    CountryResponse response = dbReader.country(ipAddress);

    return response.getCountry().getName();
}

test.war/ test.war/WEB-INF/classes


Solution

  • You can try this

    InputStream is = this.getClass().getClassLoader().getResourceAsStream("GeoLite2-Country.mmdb");