原文:【猪猪-后端】过滤IP格式工具类,将IP地址格式化,开发必备工具。
源代码下载地址:http://www.zuidaima.com/share/1550463556340736.htm
通常我们在开发中会遇到如下情况,IP:192.168.000.001,存放到数据库时我们需要,192.168.0.1,此时就需要过滤IP进行格式化。
package com.zuidaima.service.util;
/**
*
* @author www.zuidaima.com
*
*/
public class IPFormat {
public static void main(String[] args) {
IPFormat ipFormat=new IPFormat();
System.out.println("原始IP:192.168.000.001,转换结果:"+ipFormat.IPFormatTo0("192.168.000.001"));
System.out.println("原始IP:192.168.0.1,转换结果:"+ipFormat.IPFormatTo000("192.168.0.1"));
}
public static String IPFormatTo0(String ipAddress){
String[] strs = ipAddress.split("\\.");
int ip1 = Integer.valueOf(strs[0]).intValue();
int ip2 = Integer.valueOf(strs[1]).intValue();
int ip3 = Integer.valueOf(strs[2]).intValue();
int ip4= Integer.valueOf(strs[3]).intValue();
String ip=String.format("%1$01d.%2$01d.%3$01d.%4$01d", ip1,ip2,ip3,ip4);
return ip;
}
public static String IPFormatTo000(String ipAddress){
String[] strs = ipAddress.split("\\.");
int ip1 = Integer.valueOf(strs[0]).intValue();
int ip2 = Integer.valueOf(strs[1]).intValue();
int ip3 = Integer.valueOf(strs[2]).intValue();
int ip4= Integer.valueOf(strs[3]).intValue();
String ip=String.format("%1$03d.%2$03d.%3$03d.%4$03d", ip1,ip2,ip3,ip4);
return ip;
}
}