复制全国行政区划内容到一个txt文件,改为utf-8格式(打开文件另存为另一个文件时可以选择编码)
http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201703/t20170310_1471429.html
以下便是逐行读取到一个map对象中的代码
package com.vtradex.ehub.lbs.utils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.org.apache.commons.codec.Charsets;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
public class AdministrativeArea {
private static HashMap<String, String> map = Maps.newHashMap();
private static Logger logger=LoggerFactory.getLogger(AdministrativeArea.class);
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
* @return
*/
static{
File file = new File(AdministrativeArea.class.getResource("/AdministrativeArea.txt").getFile());
List<String> list;
String code,name;
try {
list = Files.readLines(file, Charsets.UTF_8);
for (String tempString : list) {
if (!tempString.equals("")) {
code=getCode(tempString);
name=getChinese(tempString);
//市辖区不用存储
if(name.equals("市辖区")) {
name="";
}
map.put(code,name);
}
}
logger.info("全国行政区:"+JSON.toJSONString(map));
} catch (IOException e) {
logger.error("读取全国行政区失败,检查是否存在文件和文件编码是否为utf-8");
e.printStackTrace();
}
}
public static String getMatcher(String regex, String str) {
String result = "";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
result = matcher.group(1);
}
return result;
}
//截取编码
protected static String getCode(String str) {
return getMatcher("(\\d+).*", str);
}
//截取行政区名称
protected static String getChinese(String str) {
return getMatcher("([\u4e00-\u9fa5].*)", str);
}
//判断字符串是否匹配正则
public static boolean matches(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
//判断是否为行政区编码
public static boolean isAreaCode(String code) {
String regex="[1-9]\\d{5}(?!\\d)";
return matches(regex, code);
}
public static String getNameByCode(String code) {
//判断字符串长度是否为6位
if(code==null||code.equals("")||!isAreaCode(code)) {
return "";
}
String name="";
//根据行政区规则,判断是否有上一级行政区,最后两位不为0说明是三级行政区,中间两位
String provinceCode=code.substring(0, 2)+"0000";
String cityCode=code.substring(0, 4)+"00";
//获取省份
if(code.equals(provinceCode)) {
name=map.get(provinceCode);
}else if(code.equals(cityCode)) {
name=map.get(provinceCode)+map.get(cityCode);
}else {
name=map.get(provinceCode)+map.get(cityCode)+map.get(code);
}
return name;
}
public static void main(String[] args) {
System.out.println(getNameByCode("445102"));
}
}
原文:http://www.cnblogs.com/Ebird/p/7427819.html