【问题标题】:Java geoip2 java.io.FileNotFoundException:Java geoip2 java.io.FileNotFoundException:
【发布时间】:2020-08-14 00:22:16
【问题描述】:

我使用 geoip2 通过 ip 来确定国家。在代码的开发和测试过程中,我没有任何问题,但是当我运行编译的归档时,我遇到了 java.io.FileNotFoundException 异常。我知道这是因为文件的路径是绝对的,并且在存档中它会更改。问题:我需要如何更改我的代码,以便即使从存档中我也可以访问该文件?

   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

【问题讨论】:

  • 无论是纯java代码还是你使用的任何框架

标签: java file geoip2


【解决方案1】:

你可以试试这个

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

【讨论】:

  • java.io.FileNotFoundException: 文件:\C:\Users\general\Desktop\test\target\test.war!\GeoLite2-Country.mmdb
  • 你确定 GeoLite2-Country.mmdb 是战争文件的一部分吗?战争文件中的相对位置是什么?是 src/main/resources/GeoLite2-Country.mmdb 吗?
  • 在项目目录下:src\main\resources\GeoLite2-Country.mmdb;存档中:test.war\WEB-INF\classes\GeoLite2-Country.mmdb;
  • 我很确定 GeoLite2-Country.mmdb 不在您的战争文件中,否则它永远不会抛出 java.io.FileNotFoundException: file:\C:\Users\general\Desktop\test \target\test.war!\GeoLite2-Country.mmdb
  • 附档案结构的帖子图片
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多