您的位置:首页 > 其它

统计一个文件中重复行的个数,并打印出内容

2015-01-30 14:11 169 查看
分析试题

1、统计文件,肯定涉及到文件的读取操作,考察IO的操作。

2、统计这块,考察的是集合框架的Map集合的添加,遍历

public static void test(String filepath)
	{
		try
		{
			File file = new File(filepath);
			if(!file.exists())
			{
				System.out.println("file not exist");
				return;
			}

			//create BufferedReader to improve efficient
			BufferedReader bufReader = new BufferedReader(new FileReader(file));
			String line = null;

			//create map collection to record information
			Map<String,Integer> map = new HashMap<String,Integer>();
			while((line = bufReader.readLine()) != null)
			{
				if(map.containsKey(line))
					map.put(line,map.get(line)+1);
				else
					map.put(line,1);
			}
			//print map collction
			showMap(map);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
	private static void showMap(Map<String,Integer> map)
	{
		if(map == null)
			return;
		Set<String> keyset = map.keySet();
		Iterator<String> it = keyset.iterator();
		while(it.hasNext())
		{
			String s = it.next();
			System.out.println( s+ "......" + map.get(s));
		}
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐