62,623
社区成员
发帖
与我相关
我的任务
分享import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IPTest {
public static void main(String[] args) {
File oldFile = new File("1.txt");
File newFile = new File("_1.txt");
IPUtil util = new IPUtil();
util.convertToFile(oldFile, newFile);
System.out.println("ok!");
}
}
class IPData {
private String ip1;
private String ip2;
private String nation;
private String name;
private long longIp1;
private long longIp2;
public String getIp1() {
return ip1;
}
public void setIp1(String ip1) {
this.ip1 = ip1;
this.longIp1 = IPUtil.ipToLong(ip1);
}
public String getIp2() {
return ip2;
}
public void setIp2(String ip2) {
this.ip2 = ip2;
this.longIp2 = IPUtil.ipToLong(ip2);
}
public long getLongIp1() {
return longIp1;
}
public long getLongIp2() {
return longIp2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String toString() {
return String.format("%s(%d), %s(%d), %s, %s", ip1, longIp1, ip2, longIp2, nation, name);
}
public String toNumString() {
return String.format("%d,%d,%s,%s", longIp1, longIp2, nation, name);
}
}
class IPUtil {
/**
* 将IP地址转为long数据
* @param strIP
* @return
*/
public static long ipToLong(String strIP) {
String[] ips = strIP.split("\\.");
long[] ip = new long[ips.length];
for (int i = 0; i < ips.length; i++) {
ip[i] = Long.parseLong(ips[i]);
}
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
/**
* 进行文件转换(将IP地址转为long数据)
* @param oldFile
* @param newFile
*/
public void convertToFile(File oldFile, File newFile) {
BufferedReader br = null;
BufferedWriter bw = null;
String line = System.getProperty("line.separator");
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String str = null;
while ((str = br.readLine()) != null) {
IPData ipdata = toIPData(str.trim());
bw.write(ipdata.toNumString() + line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 分隔旧文件行串
* @param str
* @return
*/
private IPData toIPData(String str) {
String[] strs = str.split("\\s+");
IPData ipdata = new IPData();
ipdata.setIp1(strs[0]);
ipdata.setIp2(strs[1]);
ipdata.setNation(strs[2]);
ipdata.setName(strs[3]);
return ipdata;
}
}