-1

我开发了一个应用程序,它读取 java 项目内的 java 包中有多少文件,并计算这些单独文件中的代码行,例如在 java 项目中,如果有 2 个包有 4 个单独的文件,则读取的文件总数将是 4,如果这 4 个文件在每个文件中有 10 行代码,那么 4*10 在整个项目中总共有 40 行代码......下面是我的一段代码

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

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

            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; ) {
                            while (scanner.hasNextLine()) {
   String line = scanner.nextLine().trim();
   if (!line.isEmpty()) {
     lineCount++;
   }
                        }
                    } catch (NoSuchElementException e) {
                        result.put(file, lineCount);
                        totalLineCount += lineCount;
                    }
                }
            }

        }

        /**
         * 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);
            }
        }

但问题是它在计算单个文件的代码行时也会计算空白行,它不应该,请告知我需要在我的程序中做哪些修改,以便它在计算时不计算空白行单个文件的代码行。

我想到的想法只是将读取的字符串与“”进行比较,如果不等于“”(空)则计数 if(!readString.trim().equals("")) lineCount++ 请为此提供建议

4

1 回答 1

2

建议:

  • 扫描仪有一个hasNextLine()你应该使用的方法。我会用它作为while循环的条件。
  • 然后通过在循环内调用nextLine()一次来获取 while 循环内的行。
  • 再次调用trim()您读入的字符串。在最新的代码更新中,我仍然没有看到您的尝试!
  • 在 Strings 上调用方法时的一个关键概念是它们是不可变的,并且在它们上调用的方法不会改变底层 String,并且trim()没有什么不同:调用它的 String 是不变的,但方法返回的 String改变了,实际上是修剪过的。
  • String 有一个isEmpty()方法,你应该在修剪 String 后调用它。

所以不要这样做:

try {
    for (lineCount = 0; scanner.nextLine() != null; ) {
        if(!readString.trim().equals("")) lineCount++; // updated one
    }
} catch (NoSuchElementException e) {
    result.put(file, lineCount);
    totalLineCount += lineCount;
}

而是这样做:

int lineCount = 0;
while (scanner.hasNextLine()) {
   String line = scanner.nextLine().trim();
   if (!line.isEmpty()) {
     lineCount++;
   }
}
于 2012-07-01T04:34:32.020 回答