最近写了一个读取文本的类 由于是把文件以字符串的形式读取出来 所以我选择了以char为单位读取而非通常的以byte为单位读取 根据需求 我必须要知道这个文件一共有多少char 看了很多java的api 没发现有这个功能的 所以想让大家来帮助我一下
------解决方案--------------------
统计字符串str中小写字母,大写字母,数字的个数
- Java code
Matcher match = Pattern.compile("[a-z]").matcher(str); while (match.find()) lCount++; match = Pattern.compile("[A-Z]").matcher(str); while (match.find()) uCount++; match = Pattern.compile("\\d").matcher(str); while (match.find()) nCount++;
------解决方案--------------------
- Java code
String fileName = "D:" + File.separator + "hello.txt"; File file = new File(fileName); Reader reader = new InputStreamReader(new FileInputStream(file)); int temp = 0; String s = ""; while ((temp = reader.read()) != -1) { s += (char)temp; } reader.close(); System.out.println(s.length());//char长度 System.out.println(s);
------解决方案--------------------
java中一个char是两个字节
读入的时候统计下byte,是不是就可以得到char数
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
中文会不会读出乱码???
------解决方案--------------------
自己统计一下就可以了
for example
- Java code
BufferedReader br = new BufferedReader(new FileReader("xxx"));int count = 0, read = 0;while ((read=br.read()) != -1) { count++;}br.close();System.out.printf("char count = %d\n", count);
------解决方案--------------------
1个字母:1 byte
1个汉字(gbk):2 byte
1个汉字(utf-8):3 byte
读一行,取得String的长度,进行累加。如果是要含回车符则加1,不含则不加。
制取字母的话,char转换为byte的长度为1就是,否则不是。
这看你的具体要求是什么?char只是只字母还是可以包含汉字。
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------