代码行数统计的Java和Python实现

通过编写程序来统计文件的行数,可以在巩固文件IO知识的同时计算出自己的代码量,以下分别提供JavaPython实现的版本。

解决思路

两种版本的思路几乎相同,每一个文件夹(目录)内的行数都是其所有子文件夹子文件的行数和,以此类推。即以类似于深度优先搜索的方法来递归遍历整个初始目录,遇到目录就继续向深一层搜索,遇到文件就判断是否为指定后缀的文件,如果是就通过读取文件计算其行数并不断累加。

Java实现

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class CountLine {
    //计算顶层目录下所有指定文件的行数
    public static int count(String root, String item) throws IOException {
        return count(new File(root), item);
    }

    //计算某一路径下所有指定文件的行数
    private static int count(File path, String item) throws IOException {
        int sum = 0;
        File[] list = path.listFiles();
        if (list != null) {
            for (File f : list) {
                sum += count(f, item);          //遇目录,递归
            }
        }
        else {                                  //遇文件,计算行数
            if (path.getName().endsWith(item)) {
                sum = countFileLine(path.getAbsolutePath());
            }
        }

        return sum;     
    }

    //计算文件行数
    private static int countFileLine(String filename) throws IOException {
        FileReader fr = null; 
        BufferedReader br = null;
        int count = 0;
        try {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
            while (true) {
                String s = br.readLine();
                if (s == null)      break;
                count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            fr.close();
            br.close();
        }
        return count;
    }


    public static void main(String[] args) throws IOException {
        String root = "C:\\Users\\Administrator\\Desktop\\Code";        //指定初始目录
        String item = ".java";                                         //指定文件后缀
        int total = count(root, item);
        System.out.println(total);
    }
}

Python实现

需要注意的是利用Python统计时,需要统一文件的编码方式,否则在读取文件解码时会出现错误,最好统一为utf-8编码。关于批量实现文件转码的方法可参考 http://blog.csdn.net/zhayujie5200/article/details/78727677

import os
#计算文件行数
def count_file(file_name):
    with open(file_name, 'r', encoding = 'utf-8') as f:
        num = len(f.readlines())
    return num

#统计该路径下文件行数
def count(path, item):
    sum = 0                         #当前路径(目录或文件)内的行数
    if not os.path.isdir(path):
        if os.path.splitext(path)[1] == item:
            sum = count_file(path)
        return sum

    else:
        for file_name in os.listdir(path):
            sum += count(os.path.join(path, file_name), item)
    return sum

if __name__ == '__main__':
    root = 'C:\\Users\\Administrator\\Desktop\\Code'
    item = '.py'
    total_line = count(root, item)
    print(total_line)

猜你喜欢

转载自blog.csdn.net/zhayujie5200/article/details/78813988