File stream = new File("d:/test.txt");
int num = 0; //数字数
int letter = 0; //字母数
int line = 0; //行数
int space = 0; //空格数
int word= 0; //汉字数
BufferedReader reader=new BufferedReader(new FileReader(stream));//字符流方式获取
BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream(stream));//字节流方式获取
String str=null;
//while((str=reader.readLine())!=null){
int counts;
byte []byt=new byte[10240];
while((counts=inputStream.read(byt, 0, byt.length))!=-1){
str=new String(byt, 0, counts);
System.out.println(str);
//line++;//行数统计
line+=countLine(str); //数字统计
num+=countNumer(str); //数字统计
letter+=countLetter(str);//字母
space+=countSpace(str);//空格
word+=countWord(str);//汉字
}
//字符流方式获取
while((str=reader.readLine())!=null){
System.out.println(str);
line++;//行数统计
//line+=countLine(str); //数字统计
num+=countNumer(str); //数字统计
letter+=countLetter(str);//字母
space+=countSpace(str);//空格
word+=countWord(str);//汉字
}
System.out.println(line);
System.out.println(num);
System.out.println(letter);
System.out.println(space);
System.out.println(word);
reader.close();
inputStream.close();
}
//统计行数
private static int countLine(String str) {
int line = 0; //字母数
Pattern pattern = Pattern.compile("\\n");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
line++;
}
return line;
}
//统计汉字
private static int countWord(String str) {
int word = 0; //字母数
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
word++;
}
return word;
}
//统计空格
private static int countSpace(String str) {
int space = 0; //字母数
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
space++;
}
return space;
}
//统计文件中出现的字母
private static int countLetter(String str) {
int letter = 0; //字母数
Pattern pattern = Pattern.compile("[a-zA-Z]");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
letter++;
}
return letter;
}
//统计字符串中一行中出现中的数字
private static int countNumer(String str) {
int count = 0;
Pattern pattern=Pattern.compile("\\d");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
count++;
}
return count;
}