问题回顾
项目工程结构重构成基于maven模块化管理,运行编译后的jar无法读取ip2region.db配置文件,抛出异常:FileNotFoundException.
问题处理
初始代码
//db
String dbPath = AddressUtils.class.getResource("/ip2region.db").getPath();
File file = new File(dbPath);
if (file.exists() == false) {
Console.log("Error: Invalid ip2region.db file");
}
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, dbPath);
问题修复
// 读取jar包内的配置文件信息
ClassPathResource resource = new ClassPathResource("/ip2region.db");
InputStream inputStream = resource.getInputStream();
byte[] dbBinStr = IoUtil.readBytes(inputStream);
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, dbBinStr);
// 查询算法memory,采用二进制方式初始化DBSearcher需要使用MEMORY_ALGORITYM,
//否则会抛出null。
Method method = searcher.getClass().getMethod("memorySearch", String.class);
String ip = ((DataBlock) method.invoke(searcher, ip)).getRegion();
外链
参考链接:https://gitee.com/lionsoul/ip2region/issues/IILFL
mica开源的ip2region boot stater:https://segmentfault.com/a/1190000022622489