计算IP地址 备份

该代码段展示了如何在Java中实现一个IP地址查询服务。通过读取本地的IP到区域映射数据库文件,利用`ip2region.xdb`进行IP定位,获取到省市区信息,并进行格式化处理,返回最终的地址。在处理过程中,还进行了异常处理和资源的关闭操作。
摘要由CSDN通过智能技术生成

@Slf4j
public class IPUtils {

		public static String getAddress(String ip) throws IOException {
		//如果传进来的ip为空,就直接返回空串
		if (Func.isBlank(ip)) {
			return "";
		}
		
		//获取流
		InputStream inputStream = IPUtils.class.getResourceAsStream("/ip/ip2region.xdb");
		if (Func.isNull(inputStream)) {
			log.error("没有找到计算IP地址数据文件");
			return "";
		}
		//新建备份文件
		File file = new File("/ip/ip2regionCopy.xdb");
		//将流中的信息写入备份文件中
		FileUtils.copyInputStreamToFile(inputStream, file);
		String dbPathService = file.getPath();

		Searcher searcher = null;
		try {
			searcher = Searcher.newWithFileOnly(dbPathService);
		} catch (IOException e) {
			log.info("初始化xdb数据文件错误" + e.getMessage());
		}


		log.info("服务路径:" + dbPathService);

		// 2、查询

		String region = "";
		try {
			region = searcher.search(ip);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		log.info(region);


		String address = "";
		try {
			address = changeAddress(region);
		} catch (Exception e) {
			log.info("转换地址失败" + e.getMessage());
			log.error(e.getMessage());
			return "";
		}

		log.info("最后地址:" + address);

		// 3、关闭资源
		searcher.close();
		inputStream.close();

		log.info("起始---------------------------------------------------------");

		return address;

		// 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
	}

	//只取省市区
	private static String changeAddress(String region) {
		StringBuilder address = new StringBuilder();

		if (Func.isNoneBlank(region)) {
			if (region.contains("内网IP")) {
				return "";
			}

			List<String> areas = Arrays.asList(Func.split(region, "|"));
			address.append(
				Func.equals(areas.get(0), "0") ? "" : (areas.get(0) + "-")
			).append(
				Func.equals(areas.get(2), "0") ? "" : (areas.get(2) + "-")
			).append(
				Func.equals(areas.get(3), "0") ? "" : areas.get(3) + "-"
			);


			address = new StringBuilder(address.substring(0, address.length() - 1));

		}

		return address.toString();

	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值