【问题标题】:Regarding excluding of commented lines关于排除注释行
【发布时间】:2012-07-01 06:31:26
【问题描述】:

我正在尝试开发计算我的源文件的代码行数的应用程序..

package asd;
    public class abv {
        /**
         * @param args
         */
        public static void main(String[] args) {
    // comment
    /* comment*/
        }
    }

下面是这段代码.....

 private static int totalLineCount = 0;
    private static int totalFileScannedCount = 0;

    public static void main(final String[] args) throws Exception {

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
        chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            Map<File, Integer> result = new HashMap<File, Integer>();
            File directory = new File(chooser.getSelectedFile().getAbsolutePath());

            List<File> files = getFileListing(directory);

            // print out all file names, in the the order of File.compareTo()
            for (File file : files) {
               // System.out.println("Directory: " + file);
                getFileLineCount(result, file);
                //totalFileScannedCount += result.size(); //saral
            }

            System.out.println("*****************************************");
            System.out.println("FILE NAME FOLLOWED BY LOC");
            System.out.println("*****************************************");

            for (Map.Entry<File, Integer> entry : result.entrySet()) {
                System.out.println(entry.getKey().getAbsolutePath() + " ==> " + entry.getValue());
            }
            System.out.println("*****************************************");
            System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount);
            System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount);
        }

    }


    public static void getFileLineCount(final Map<File, Integer> result, final File directory)
            throws FileNotFoundException {
        File[] files = directory.listFiles(new FilenameFilter() {

            public boolean accept(final File directory, final String name) {
                if (name.endsWith(".java")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        for (File file : files) {
            if (file.isFile()) {
                Scanner scanner = new Scanner(new FileReader(file));
                int lineCount = 0;
                totalFileScannedCount ++; //saral
                try {

                    /*for (lineCount = 0; scanner.nextLine() != null;lineCount++ ) { //saral
                        ;


                    }*/


                    while (scanner.hasNextLine()) {
                           String line = scanner.nextLine().trim();
                           if (!line.isEmpty()) {
                              System.out.println("debug-->"+line); // to debug cross checked that no whitespaces are there 
                             lineCount++;
                           }
                    }

                     result.put(file, lineCount);
                     totalLineCount += lineCount;                               
                } catch (NoSuchElementException e) {
                    // e.printStackTrace();
                }
            }
        }

    }

    /**
     * Recursively walk a directory tree and return a List of all Files found;
     * the List is sorted using File.compareTo().
     * 
     * @param aStartingDir
     *            is a valid directory, which can be read.
     */
    static public List<File> getFileListing(final File aStartingDir) throws FileNotFoundException {
        validateDirectory(aStartingDir);
        List<File> result = getFileListingNoSort(aStartingDir);
        Collections.sort(result);
        return result;
    }

    // PRIVATE //
    static private List<File> getFileListingNoSort(final File aStartingDir) throws FileNotFoundException {
        List<File> result = new ArrayList<File>();
        File[] filesAndDirs = aStartingDir.listFiles();
        List<File> filesDirs = Arrays.asList(filesAndDirs);
        for (File file : filesDirs) {
            if (file.isDirectory()) {
                result.add(file);
            }
            if (!file.isFile()) {
                // must be a directory
                // recursive call!
                List<File> deeperList = getFileListingNoSort(file);
                result.addAll(deeperList);
            }
        }
        return result;
    }

    /**
     * Directory is valid if it exists, does not represent a file, and can be
     * read.
     */
    static private void validateDirectory(final File aDirectory) throws FileNotFoundException {
        if (aDirectory == null) {
            throw new IllegalArgumentException("Directory should not be null.");
        }
        if (!aDirectory.exists()) {
            throw new FileNotFoundException("Directory does not exist: " + aDirectory);
        }
        if (!aDirectory.isDirectory()) {
            throw new IllegalArgumentException("Is not a directory: " + aDirectory);
        }
        if (!aDirectory.canRead()) {
            throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
        }
    }

现在问题来了。当我选择项目文件夹并在控制台上查看结果时,它会计算我的 java 文件的代码行,但它也计算 cmets,我什至不希望计算 cmets,这意味着不计算注释行作为代码行,请告知需要在这段代码中进行哪些修改...

下面是我在控制台上的输出..

debug-->package asd;
debug-->public class abv {
debug-->/**
debug-->* @param args
debug-->*/
debug-->public static void main(String[] args) {
debug-->// comment
debug-->/* comment*/
debug-->}
debug-->}
*****************************************
FILE NAME FOLLOWED BY LOC
*****************************************
C:\Users\vaio\Desktop\Demo\fg\src\asd\abv.java ==> 10
*****************************************
SUM OF FILES SCANNED ==>    1
SUM OF ALL THE LINES ==>    10

请告知需要在这段代码中进行哪些修改...

【问题讨论】:

    标签: java string collections io


    【解决方案1】:

    我的第一个尝试是使用正则表达式。鉴于源文件不会那么大,您可以将整组行读入一个字符串,运行一个将所有 cmets 替换为空的正则表达式,然后计算新字符串中的行数。

    我的 Java 有点生疏,但我相信这会奏效(目前没有要测试的环境):

    int count = 0;
    Scanner scanner = new Scanner(new File(file));
    scanner.useDelimiter("\\Z");
    String data = scanner.next();
    String cleaned = data.replaceAll("/\\*(?:.|[\\n\\r])*?\\*/",""));
    LineNumberReader lnr = new LineNumberReader(new StringReader(cleaned));
    String line;
    while ((line = lnr.readLine()) != null)
    {
        String sline = line.trim();
        if(sline.isEmpty() == false)
            if(!(sline.length() > 2 && sline.charAt(0) == '/' && sline.charAt(1) == '/'))
                count += 1;
                //separated for clarity
    }
    

    这应该为您提供不都是注释的行数 // 并且还可以处理多行 cmets。

    cmets 正则表达式的来源:Regex source

    【讨论】:

      【解决方案2】:

      我之前的回答不正确。因为你勾选它是正确的所以我使用了代码 @Trickfire 编辑我的答案。

      while (scanner.hasNextLine()) {
      
                         scanner.useDelimiter("\\Z");
                         String data = scanner.next();
                         String cleaned = data.replaceAll("/\\*(?:.|[\\n\\r])*?\\*/",""));
                         LineNumberReader lnr = new LineNumberReader(new StringReader(cleaned));
                         String line;
                         while ((line = lnr.readLine()) != null)
                          {
                            String sline = line.trim();
                            if(sline.isEmpty() == false)
                            if(!(sline.length() > 2 && sline.charAt(0) == '/' && sline.charAt(1) == '/'))
                                lineCount += 1;
                                 //separated for clarity
                         }
      
      
                      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 1970-01-01
        • 2014-10-17
        • 2010-09-24
        相关资源
        最近更新 更多