日期:2014-05-20 浏览次数:20870 次
public void getPhoneAttribution(String cityname) { try{ BufferedWriter bw = new BufferedWriter(new FileWriter("cityregion.data",true)); String cityName1=cityname+"区"; String cityName2=cityname+"市"; if (telMap.containsValue(cityName1)) { bw.write("\n"+cityName1+" "); bw.write(telMap.get(cityName1)); }else{ if (telMap.containsValue(cityName2)) { bw.write("\n"+cityName2+" "); bw.write(telMap.get(cityName2)); }else { System.out.println("the city's region is null!"); } } bw.flush(); bw.close(); }catch(Exception e){ e.printStackTrace(); } }
------解决方案--------------------
//讀出1.txt中的內容 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\1.txt"), "BIG5")); Map<String, String> fa = new HashMap<String, String>(); String temp = null; while ((temp = br.readLine()) != null) { fa.put(temp.split(" ")[0], temp.split(" ")[1]); } br.close(); //讀出2.txt中的內容與fa中的內容進行匹配 BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\2.txt"), "BIG5")); Map<String, String> fa1 = new HashMap<String, String>(); String temp1 = null; while ((temp1 = br1.readLine()) != null) { for (Iterator<Entry<String, String>> it = fa.entrySet().iterator(); it.hasNext();) { Entry<String, String> e = it.next(); if (e.getValue().matches(".*" + temp1 + ".*")) { fa1.put(e.getKey(), temp1); } } } br1.close(); //寫到新文件 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:\\3.txt"), "BIG5")); for (Iterator<Entry<String, String>> it = fa1.entrySet().iterator(); it.hasNext();) { Entry<String, String> e = it.next(); bw.write(e.getKey() + " " + e.getValue() + " \r\n"); } bw.flush(); bw.close();