---
title: "[原创]java写的字符统计高速算法"
author: "kong0itey"
date: "2011-08-10T20:47:32Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-08-15T01:19:16Z"
id: 1145065
url: "https://kongcodecenter.iteye.com/blog/1145065"
---

```java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class Test {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		test();
	}

	public static void test() throws IOException {
		//读取文件内容到字符串
		String src = "D:\\workspace\\max\\src\\1.txt";// 这是你的文件的绝对径录及文件名
		File f = new File(src);
		BufferedReader br = new BufferedReader(new FileReader(f));
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		//查找字符串中字符出现频率
		String text = sb.toString();
		long t1 = System.currentTimeMillis();
		final int STR_LEN = text.length();
		final int CHAR_COUNT = Character.MAX_VALUE + 1;
		final char[] textChars = text.toCharArray();
		int[] times = new int[char_count];
		for (int i = 0; i < STR_LEN; i++) {
			times[textchars[i]]++;
		}
		int t = 0;
		char c = 0;
		for (int i = 0; i < CHAR_COUNT; i++) {
			if (times[i] > t) {
				t = times[i];
				c = (char) i;
			}
		}
		long t2 = System.currentTimeMillis();
		System.out.println("从" + STR_LEN + "个字符中查找完毕，出现次数最多的字符是" + c
				+ "，该字符的ascii编号为" + (int) c + "，它一共出现了" + t + "次.执行本次查找，总共耗时"
				+ ((t2 - t1) / 1000.0) + "秒");
	}

}

```