Java and Python implementation of lines of code counting

By writing a program to count the number of lines in a file, you can consolidate the knowledge of file IO and calculate your own code amount. The following versions provide Java and Python implementations.

Solutions

The idea of ​​​​the two versions is almost the same, the number of lines in each folder (directory) is the sum of the number of lines in all its subfolders or subfiles , and so on. That is, recursively traverse the entire initial directory in a method similar to depth-first search , continue to search deeper when encountering a directory , and determine whether it is a file with the specified suffix when encountering a file, and if so, calculate the number of lines by reading the file. and keep adding up.

Java implementation

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 implementation

It should be noted that when using Python statistics, it is necessary to unify the encoding method of the file, otherwise an error will occur when reading the file and decoding, it is best to unify the utf-8encoding. For the method of batch transcoding files , please refer to 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935759&siteId=291194637
Recommended