Java -----将省市区的txt文件转化为map的字典
昨天学了iOS的省市区的txt文件转化为键值对列表,类似JSON数据格式的数据,今天正好星期日, 闲来无事, 便想着用以前自学的Java实现一样的功能.
终于, 功夫不负有心人,写完了.
1 package province; 2 import java.awt.List; 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.InputStreamReader; 7 import java.util.ArrayList; 8 import java.util.Dictionary; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 import javax.sound.sampled.AudioFormat.Encoding; 13 14 public class Province { 15 public static void main(String[] args){ 16 // System.out.print("hello world"); 17 /** 读取文件到string数组当中 */ 18 String encoding = "UTF-8"; 19 Map map = new HashMap(); 20 String strings[] = new String[1000] ; 21 int i = 0; 22 try { 23 File file = new File("/Users/dllo/Downloads/area.txt"); 24 if(file.isFile() && file.exists()){ //判断文件是否存在 25 InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding); 26 BufferedReader bufferReader = new BufferedReader(read); 27 String lineText = null; 28 while((lineText = bufferReader.readLine()) != null){ 29 30 strings[i] = lineText; 31 i += 1; 32 } 33 } 34 } catch (Exception e) { 35 // TODO: handle exception 36 } 37 38 String province = ""; //保存上一个省名的变量 39 String city = ""; //保存上一个市名的变量 40 int n = 0; 41 for (String string : strings) { 42 43 if (!string.startsWith(" ")) { //检查是否不以空格开头----省名 44 HashMap<Object, Object> map2 = new HashMap<>(); //新建市的字典(hashmap), 键是省名,值是市名 45 map.put(string, map2); 46 province = string ; 47 }else if (!string.startsWith(" ")) { //检查是否以4个空格开头----市名 48 ArrayList<String> strings2 = new ArrayList<String>(); //新建区名数组 49 Map map3 = (Map)map.get(province); 50 map3.put(string, strings2); 51 city = string; 52 n = 0; 53 }else{ //区名 54 ArrayList<String> string3 = (ArrayList<String>) ((Map) map.get(province)).get(city);//找到要添加区名的数组 55 string3.add(string); 56 } 57 } 58 59 System.out.println(map); //输出map 60 } 61 }
area.txt文件和iOS里面的文件一样.