日期:2014-05-19 浏览次数:21176 次
package com.zf.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test5 {
public static void parser() throws Exception{
Map<String , List<String>> map = new LinkedHashMap<String, List<String>>();
Map<String, String[]> result = new LinkedHashMap<String, String[] >();
File file = new File("E:\\360data\\重要数据\\桌面\\input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
Pattern p1 = Pattern.compile("^(\\d+)*+");
Pattern p2 = Pattern.compile("\\[.+?\\]");
Pattern p3 = Pattern.compile("\\d+");
while((line = br.readLine()) != null){
Matcher m1 = p1.matcher(line);
Matcher m2 = p2.matcher(line);
String tmp = null;
if(m1.find()){
tmp = m1.group(1);
if(!map.containsKey(tmp))
map.put(tmp, new LinkedList<String>() );
}
if(m2.find()){
String str = m2.group();
Matcher m3 = p3.matcher(str);
while(m3.find()){
map.get(tmp).add(m3.group());
}
}
}
//去掉单个元素
Set<String> keySet = map.keySet();
for (String key : keySet) {
List<String> val = map.get(key);
for (int i = val.size() - 1; i >= 0 ; i--) {
String s = val.remove(i);
if(val.contains(s)){
val.add(s);
}
}
}
//去掉重复元素 ,得到结果集
Set<String> ks = map.keySet();
for (String key : ks) {
List<String> val = map.get(key);
HashSet<String> set = new HashSet<String>(val);
String arr[] = set.toArray(new String[set.size()]);
Arrays.sort(arr); //排序
result.put(key, arr);
}
//写入文件
File outFile = new File("E:\\360data\\重要数据\\桌面\\output.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
Set<Entry<String, String[]>> set = result.entrySet();
for (Entry<String, String[]> entry : set) {
if(entry.getValue().length > 0){
bw.write(entry.getKey() + " " + Arrays.toString(entry.getValue()) + "\r\n");
}
}
bw.flush() ; bw.close();
}
public static void main(String[] args) throws Exception {
parser();
System.out.println("OK");
}
}
------解决方案--------------------
http://topic.csdn.net/u/20120624/21/9357067a-552c-4200-a16c-f0924f4b2da6.html