【Java I/O流操作实例】如何用Java程序统计代码行数。

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)+"毫秒");
	}
}

在这里插入图片描述
运行截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值