Chinaunix首页 | 论坛 | 博客
  • 博客访问: 189393
  • 博文数量: 92
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1413
  • 用 户 组: 普通用户
  • 注册时间: 2013-02-04 21:12
文章分类
文章存档

2013年(92)

我的朋友

分类: 信息化

2013-03-03 05:31:04

[代码] [Java]代码 import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.uti ; l.Iterator;
import java.util.Map;
import java.util.Set;

public class CharactersUtils {

	/**
	 * 获取文档中呈现的最多字符及数量
	 * @param path 文档途径。txt
	 * @return 最多的字符,key为字符,value为数量
	 */
	public static Map maxCountOfCharacters(String path) {

		if (path == null) {
			throw new NullPointerException("path");
		}

		Map characterCounts = getCharactersCount(path);

		if (characterCounts == null) {
			return null;
		}

		Set keys = characterCounts.keySet();
		Iterator iterator = keys.iterator();
		int max = 0;
		Map result = new HashMap();
		while (iterator.hasNext()) {
			char currChar = iterator.next();
			int currCount = characterCounts.get(currChar);
			if (currCount > max) {
				max = currCount;
				result.clear();
				result.put(currChar, max);
			} else if (currCount == max) {
				result.put(currChar, max);
			}
		}
		return result;
	}

	/**
	 * 计算各个字符的数量
	 * @param path 文档途径
	 * @return 各个字符个数的map key为字符,value为数量
	 */
	private static Map getCharactersCount(String path) {

		File file = null;
		BufferedReader reader = null;
		Map characterCounts = null;

		try {
			file = new File(path);
			reader = new BufferedReader(new FileReader(file));
			String temp = "";
			characterCounts = new HashMap();
			while ((temp = reader.readLine()) != null) {
				if (temp.trim() != "") {
					char[] chs = temp.trim().toCharArray();
					for (char ch : chs) {
						if (characterCounts.containsKey(ch)) {
							characterCounts.put(ch, characterCounts.get(ch)   1);
						} else {
							characterCounts.put(ch, 1);
						}
					}
				}
			}
			return characterCounts;
		} catch (FileNotFoundException e) {
			throw new RuntimeException("CharactersUtils:", e);
		} catch (IOException e) {
			throw new RuntimeException("CharactersUtils:", e);
		}
	}
} ; 
阅读(509) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~