如何在java中编写一个读取文本文件并查找每个字符出现次数的方法?

时间:2014-11-08 23:07:49

标签: java file-io arraylist character

如何在java中编写一个读取文本文件并查找每个字符出现次数的方法?然后在您阅读它们时将项目存储到arraylist中。

2 个答案:

答案 0 :(得分:0)

首先打开.txt文件并阅读其内容 然后创建一个Hashmap并迭代字符以进行计数

    BufferedReader br = new BufferedReader(new FileReader(fileName));
    HashMap<Character,Integer> hm;    
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
         //iterate over the string and increment  
         //hashmap.get("character") by one
         line = br.readLine();
    }

答案 1 :(得分:0)

您可以使用FileReader打开文件,然后使用存储每个角色出现的int[]

BufferedReader br = new BufferedReader(new FileReader(fileName));
int[] characters = new int[65535];
StringBuilder sb = new StringBuilder();
int i = 0;

while ((i = br.read()) >= 0)
{
     characters[i]++;
}