import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExceptionSpider2 {
public static void main(String[] args) {
/*map用来存放发现的异常以及每种异常出现的次数*/
Map<String, Integer> map = new HashMap<String, Integer>();
/**/
BufferedReader br = null;
/*存放从文件中读取的数据行*/
String line = null;
/*用作map的key*/
String key = null;
/*定义正则表达式*/
Pattern p = Pattern.compile("(\\w+\\.)+\\w+\\.?Exception");
Matcher m = null;
try {
/*从源文件读取数据*/
br = new BufferedReader(new FileReader("E:\\text.log."));
while((line=br.readLine()) !=null) {
/**/
m = p.matcher(line);
/*匹配成功进行循环*/
while(m.find()) {
key = m.group();
/*判断是否包含key*/
if(map.containsKey(key)) {
/*包含key则value加1*/
map.put(key, map.get(key) + 1);
}else {
/*不包含则创建key*/
map.put(key, 1);
}
}
}
/*关闭打开的文件*/
br.close();
System.out.println("检索完毕");
System.out.println("一共发现了" + map.size() + "种异常");
/*遍历map*/
Iterator it = map.keySet().iterator();
while(it.hasNext()) {
String exception = (String) it.next();
int num = map.get(exception);
System.out.println("异常" + exception + "出现了: " + num + "次");
}
//System.out.println(map);
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
}
从log中查询exception出现的种类以及次数。请帮我完善下或改下格式。看着挺乱。
------解决方案--------------------
我觉得代码完全正确,调整一下结果,就可以了。建议将输入流的关闭放到finally里,同时不建议采用Iterator
- Java code
public class ExceptionSpider2 { /** * @param args */ public static void main(String[] args) { /*map用来存放发现的异常以及每种异常出现的次数*/ Map<String, Integer> map = readException(Thread.currentThread().getContextClassLoader() .getResource("text.log").getPath()); System.out.println("检索完毕"); System.out.println("一共发现了" + map.size() + "种异常"); for (String exception : map.keySet()) { int num = map.get(exception); System.out.println("异常" + exception + "出现了: " + num + "次"); } } public static Map<String, Integer> readException(String fileName) { Map<String, Integer> map = new HashMap<String, Integer>(); BufferedReader br = null; /*用作map的key*/ String key = null; /*定义正则表达式*/ Pattern p = Pattern.compile("(\\w+\\.)+\\w+\\.?Exception"); Matcher m = null; String line = null; try { /*从源文件读取数据*/ br = new BufferedReader(new FileReader(Thread.currentThread().getContextClassLoader() .getResource("text.log").getPath())); while ((line = br.readLine()) != null) { m = p.matcher(line); /*匹配成功进行循环*/ while (m.find()) { countException(map, m.group()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { /*关闭打开的文件*/ try { br.close(); } catch (IOException e) { } } return map; } private static void countException(Map<String, Integer> map, String key) { System.out.println(key); /*判断是否包含key*/ if (map.containsKey(key)) { /*包含key则value加1*/ map.put(key, map.get(key) + 1); } else { /*不包含则创建key*/ map.put(key, 1); } }}