基于Java实现的WC统计程序

JAVA学习网 2018-09-08 13:22:06

相关要求:wc.exe 是一个常见的工具,它能统计文本文件的字符数、单词数和行数。要求写一个命令行程序,模仿已有wc.exe 的功能,并加以扩充,给出某程序设计语言源文件的字符数、单词数和行数。


 

1. Github 地址:https://gitee.com/hzkkk/wc.git

2. PSP表格

PSP2.1 预估耗时(分钟) 实际耗时(分钟)
Planning    
Estimate    
Development    
Analysis    
Design Spec    
Design Review    
Coding Standard    
Design    
Coding    
Code Review    
Test    
Reporting    
Test Report    
Size Measurement    
Postmortem & Process Improvement Plan    
     

 

3. 解题思路

由于需要命令行来对程序进行控制,所以程序应该是先进行确定命令的规范形式,然后再实现对不同操作选项的命令解析,例如:wc -w -c -l filepath ,这条命令要能解析出需要对路径为filepath的文件实现词数,行数,字符数的统计功能,最后才是实现不同命令对应的统计功能。

4. 设计实现过程

包括两个类:WC、CountUtil。

WC包括主函数,主要进行命令的规范和解析;

CountUtil有三个函数

  • void count(String path, boolean c, boolean w, boolean l) 对文件进行统计,打印统计结果
  • ArrayList<File> getFiles(String path) 根据路径获取文件集合,如果路径为文件夹则调用第二个函数递归获取文件集合,为文件则直接返回
  • ArrayList<File> getFilesFromDir(String path, Boolean isDir) 递归获取文件夹下文件,返回文件集合

5. 代码说明

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            //读取控制台输入
            String command = scanner.nextLine();
            if (command.equals("exit"))
                break;
            //正则命令格式校验 格式为:wc (选项可多个)-c/w/l filepath(文件的绝对路径)
            String format = "^wc\\s+(\\-[cwl]\\s+){1,3}\\s*\\S+$";
            Pattern pattern = Pattern.compile(format);
            Matcher matcher = pattern.matcher(command);
            boolean isMatch = matcher.matches();
            if (!isMatch) {
                System.out.println("Error command!");
                break;
            }
            //选项匹配
            Pattern choosePattern = Pattern.compile("\\-[cwl]");
            Matcher chooseMatch = choosePattern.matcher(command);
            boolean c=false;
            boolean w=false;
            boolean l=false;
            while(chooseMatch.find()) {
                switch (chooseMatch.group().replace("-", "")) {
                    case "c":
                        c=true;
                        break;
                    case "w":
                        w=true;
                        break;
                    case "l":
                        l=true;
                        break;
                }
            }
            //根据最后匹配的空格索引截取文件路径
            int index = command.lastIndexOf(" ");
            String filePath = command.substring(index + 1);
            //调用count函数进行计算
            CountUtil.count(filePath,c,w,l);

        }

 6. 遇到的困难及解决方法

由于正则表达式平时很少使用,在命令的匹配中一开始多多少少会有一些出错的地方,然后再去菜鸟教程上看了一遍,最后一遍遍的测试,终于是完成了。让我巩固了正则表达式的相关的一些操作,还了解了其他一些常用的例子,体会到了正则表达式的强大。

阅读(1471) 评论(0)