代码行数统计的Java和Python实现
2017-12-15 17:38
971 查看
通过编写程序来统计文件的行数,可以在巩固文件IO知识的同时计算出自己的代码量,以下分别提供Java和Python实现的版本。
解决思路
两种版本的思路几乎相同,每一个文件夹(目录)内的行数都是其所有子文件夹或子文件的行数和,以此类推。即以类似于深度优先搜索的方法来递归遍历整个初始目录,遇到目录就继续向深一层搜索,遇到文件就判断是否为指定后缀的文件,如果是就通过读取文件计算其行数并不断累加。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)
相关文章推荐
- Python脚本实现代码行数统计代码分享
- python实现的代码行数统计(纯代码)
- 代码行数统计(python实现)
- python实现代码行数统计
- 代码行数统计(python实现)
- 代码行数统计java实现
- python实现统计代码行数的方法
- 统计代码行数(python实现)
- python实现代码行数统计示例分享
- Python脚本实现代码行数统计代码分享
- java实现统计代码行数
- 《Python Case系列》一.Python实现统计项目的代码行数
- 代码注释率统计的Python及Java实现
- python实现代码行数统计示例分享
- python实现统计代码行数的方法
- python 统计代码行数,注释行数的简单实现
- 发一个统计项目代码行数的Java代码
- Python:统计特定文件夹中,特定文件代码行数的小程序
- 统计Java程序代码行数(Java)
- 统计文件夹下java代码行数