刚在csdn上帮你解决了。
FileReader fr = new FileReader("d:\\aa.txt"); //读取流
BufferedReader br = new BufferedReader(fr); //缓冲流
FileWriter fw=new FileWriter("d:\\a2.txt"); //输出流
BufferedWriter bw=new BufferedWriter(fw); //输出缓冲流
String tempStr = "";
// 定义map key为城市名 值为list集合 存储所有city
Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
while ((tempStr = br.readLine()) != null) {
String[] tmpStrArray = tempStr.split(",");//读一行 把之分解成数组
//取得城市名 并判断是否在map已存在
if (cityMap.containsKey(tmpStrArray[1])) { //存在的情况
cityMap.get(tmpStrArray[1]).add(tmpStrArray[0]);
} else {//不存在的情况
List<String> cityList = new ArrayList<String>();
cityList.add(tmpStrArray[0]);
cityMap.put(tmpStrArray[1], cityList);
}
}
br.close();//关闭流
//************输出操作
Set<String> sStr = cityMap.keySet(); //从map中取出城市set集合并遍历
for (Iterator iterator = sStr.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
bw.write(string);
bw.newLine();
List<String> cityOutList = cityMap.get(string);
Integer size=cityOutList.size(); //不是直接输出。必须用Integer包装类来保存
bw.write(size.toString());
bw.newLine();
for (Iterator iterator2 = cityOutList.iterator(); iterator2
.hasNext();) {
String tempStr2 = (String) iterator2.next();
bw.write(tempStr2);
bw.newLine();
}
bw.newLine();
}
bw.flush();
bw.close();