日期:2014-05-20  浏览次数:20689 次

求助如何读取一个文本的char数?
最近写了一个读取文本的类 由于是把文件以字符串的形式读取出来 所以我选择了以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数
------解决方案--------------------
探讨

Java code

String fileName = "D:" + File.separator + "hello.txt";
File file = new File(fileName);
Reader reader = new InputStreamReader(new FileInputStream(file));
int temp =……

------解决方案--------------------
探讨
引用:

Java code

String fileName = "D:" + File.separator + "hello.txt";
File file = new File(fileName);
Reader reader = new InputStreamReader(new FileInputStream(file));
int temp =……

……

------解决方案--------------------
中文会不会读出乱码???
------解决方案--------------------
自己统计一下就可以了
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只是只字母还是可以包含汉字。
------解决方案--------------------
探讨

引用:

java中一个char是两个字节

读入的时候统计下byte,是不是就可以得到char数

我试了一下 用 文件长度/2 得到的char数是不正确的

引用:

1个字母:1 byte
1个汉字(gbk):2 byte
1个汉字(utf-8):3 byte

读一行,取得String的长度,进行累加。如果是要含回车符则加……

------解决方案--------------------
探讨
ok 解决了 终于发现了java自带有方法了 用带有reader的类的skip方法 实际上我
skip(Long.MAX_VALUE) 这样就可以返回文件的char数了 各位看看这样做合理不 实际上我也无从验证 但是通过使用来看感觉没什么不正常的地方

------解决方案--------------------
探讨
引用:

引用:
ok 解决了 终于发现了java自带有方法了 用带有reader的类的skip方法 实际上我
skip(Long.MAX_VALUE) 这样就可以返回文件的char数了 各位看看这样做合理不 实际上我也无从验证 但是通过使用来看感觉没什么不正常的地方
简单验证了一下跟read=br.read()用计数器算出来的一样,但是楼主忽略个问题……