读取一个目录中的文件,并且统计其中的字母,数字,空格的个数以及行数
代码实现:
/**
* @author:LYL
* @date:2011-3-9,下午04:34:23
* 读取一个目录中的文件,并且统计其中的字母,数字,空格的个数以及行数
*/
package com.lyl.exercise;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Statistics {
String path = null;
public Statistics(String path) {
this.path = path;
}
// 获取文件列表
public File[] getFile() {
File file = new File(this.path);
File[] files = file.listFiles();
return files;
}
// 获得缓冲
public BufferedReader getBuffer(File file) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
} catch (Exception e) {
e.printStackTrace();
}
return br;
}
// 获得结果数组
public int[] getResults(BufferedReader br) {
String line = null;
int letters = 0;
int numbers = 0;
int spaces = 0;
int lines = 0;
int results[];
try {
while ((line = br.readLine()) != null) {
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= 'a' && line.charAt(i) <= 'z'
|| line.charAt(i) >= 'A' && line.charAt(i) <= 'Z') {
letters++;
}
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
numbers++;
}
if (line.charAt(i) == 32) {
spaces++;
}
}
lines++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
results = new int[] { letters, numbers, spaces, lines };
return results;
}
public static void main(String[] args) {
Statistics st = new Statistics("E:" + File.separator + "Exercise");
File files[] = st.getFile();
int results[];
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
BufferedReader br = st.getBuffer(files[i]);
results = st.getResults(br);
System.out.println(files[i]);
System.out.println("字母的个数:" + results[0] + "\n数字个数:"
+ results[1] + "\n空格个数:" + results[2] + "\n行数:"
+ results[3]);
}
}
}
}