您的位置:首页 > 娱乐 > 明星 > 【已解决】ip2region解析ip获取地区位置 在linux部署出现java文件操作报错:java.io.FileNotFoundException

【已解决】ip2region解析ip获取地区位置 在linux部署出现java文件操作报错:java.io.FileNotFoundException

2024/10/5 14:40:29 来源:https://blog.csdn.net/qq_41158114/article/details/140016584  浏览:    关键词:【已解决】ip2region解析ip获取地区位置 在linux部署出现java文件操作报错:java.io.FileNotFoundException

1、依赖

        <dependency><groupId>org.lionsoul</groupId><artifactId>ip2region</artifactId><version>2.7.0</version></dependency>

2.加入ip2region.xdb文件

ip2Region下载地址

3.加入到项目里面去

把 ip2region.xdb 文件放到 resources 文件夹里面的去

在这里插入图片描述

在Maven里面添加依赖,防止把这个xdb文件编译:
在这里插入图片描述

<plugin><artifactId>maven-resources-plugin</artifactId><configuration><nonFilteredFileExtensions><nonFilteredFileExtension>xdb</nonFilteredFileExtension></nonFilteredFileExtensions></configuration>
</plugin>

4.工具类

	/*** 通过ip 获取ip所在地址* @param ip* @return*/public static String getIpAddress(String ip){if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {return "局域网 ip";}//双重校验锁方式加载对象实例(懒汉式)if (searcher == null) {synchronized (HttpServletRequestUtils.class) {if (searcher == null) {try {Resource resource = new ClassPathResource("ip2region.xdb");HttpServletRequestUtils httpServletRequestUtils = new HttpServletRequestUtils();String filePath = httpServletRequestUtils.getClass().getClassLoader().getResource("ip2region.xdb").getFile();File file= new File(filePath);log.info("文件路径:{}是否存在:{}:", filePath, file.exists());// 通过流将文件复制到file中FileUtils.writeFile(resource.getInputStream(), filePath);//下面直接获取可能会导致 java.io.FileNotFoundException 异常
//						File file = ResourceUtils.getFile("classpath:ipdb/ip2region.xdb");String dbPath = file.getPath();searcher = Searcher.newWithFileOnly(dbPath);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}}String region = null;String errorMessage = null;try {region = searcher.search(ip);} catch (Exception e) {errorMessage = e.getMessage();if (errorMessage != null && errorMessage.length() > 256) {errorMessage = errorMessage.substring(0,256);}e.printStackTrace();}// 输出 regionreturn region;}/** 读取返回结果*/private static String read(InputStream is) throws IOException {StringBuffer sb = new StringBuffer();BufferedReader br = new BufferedReader(new InputStreamReader(is));String line = null;while ((line = br.readLine()) != null) {line = new String(line.getBytes(), "utf-8");sb.append(line);}br.close();return sb.toString();}

5. 注意事项:

1.部署到线上之后:出现java文件操作报错:java.io.FileNotFoundException

java.io.FileNotFoundException: class path resource [ip2region.xdb] 
cannot be resolved to absolute file path because it does not residein the file system: 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com