I/O流文件操作实例
实现思路:程序源代码都是纯文本文件,因此我们可以使用字符流去读取文本。从根目录下递归遍历,
获得所有".java"文件,再去读取内容,每读一行则统计行数+1。
实现代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
public class SearchFile {
int line = 0; //行数
int num = 0;
public SearchFile() {
}
public void dfs(File root) throws IOException { //从根目录开始递归遍历
if(root.isDirectory()) {
File[] fileList = root.listFiles(new FileFilter() {
public boolean accept(File pathname) {
if(pathname.isDirectory()||pathname.getName().endsWith("java")) //过滤非目录和非.java文件
return true;
else
return false;
}
});
for(File f:fileList) {
if(f.isDirectory())
dfs(f); //递归
else {
countCode(f); //统计
num++;
}
}
}
}
public void countCode(File file) throws IOException { //字符流读取java文件字符行数
FileReader rd = new FileReader(file);
BufferedReader brd = new BufferedReader(rd); //使用缓冲包装类,提高读取速度
String str = null;
while((str=brd.readLine())!=null) {
if(str.length()!=0) //过滤空白行
line++; //行数+1
}
brd.close();
rd.close(); //关闭流
}
public int getLine() {
return line;
}
public int getNum() {
return num;
}
}
调用此类:
import java.io.File;
import java.io.IOException;
import com.th.model.SearchFile;
public class th {
public static void main(String[] args) {
long a = System.currentTimeMillis();
File file = new File("C:\\Users\\LX\\Desktop\\Mycode\\eclipse-workspace"); //根目录
SearchFile sf = new SearchFile();
try {
sf.dfs(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("目录 :"+file.getAbsolutePath());
System.out.println(" 共有"+sf.getNum()+"个java文件");
System.out.println(" 代码行数总计"+sf.getLine()+"行");
System.out.println(" 耗时 "+(System.currentTimeMillis()-a)+"毫秒");
}
}
运行截图