【问题标题】:Want to remove the whitespaces, with java built in methods想要删除空格,使用 java 内置方法
【发布时间】:2012-07-01 03:59:47
【问题描述】:

我开发了一个应用程序,它读取 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++ 请对此提出建议

【问题讨论】:

  • 您应该在比较它们之前修剪线条。否则,仅包含空格的行仍然会通过。
  • @Antimony 你能用你所说的逻辑更新我的代码吗,这真的有助于我理解非常感谢
  • @Naresh:他告诉你要做的就是在一个字符串上调用trim(),获取返回的修剪后的字符串,并在你的比较中使用它。当然,您可以先尝试自己做,不是吗?
  • @HovercraftFullOfEels 非常感谢支持我在这里尝试过,但它不起作用
  • 您是否遇到了包含空格的代码行问题,或者完全空白的行被计为代码行?

标签: java string io


【解决方案1】:

建议:

  • 扫描仪有一个你应该使用的hasNextLine() 方法。我会将它用作 while 循环的条件。
  • 然后通过在循环内调用一次 nextLine() 来获取 while 循环内的行。
  • 在你读入的字符串上再次调用trim()。在最新的代码更新中,我仍然没有看到你的尝试!
  • 在 String 上调用方法时的一个关键概念是它们是不可变的,在它们上调用的方法不会改变底层 String,trim() 也不例外:调用它的 String 不变,但String returned 被方法 改变了,实际上是被修剪了。
  • 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++;
   }
}

【讨论】:

  • 扫描仪scanner = new Scanner(new FileReader(file)); int lineCount = 0;总文件扫描数++; //saral try { /*for (lineCount = 0;scanner.nextLine() != null; lineCount++) { //saral ; }*/ for (lineCount = 0;scanner.nextLine() != null;) { //saral while (scanner.nextLine() != null) { } }
  • @NareshSaxena:cmets 不能保存代码。请参阅我的答案的编辑。
  • ..不,那也行不通我也尝试过您的编辑代码,但是在执行时,所有行中的一些都变成了o ..!!
  • 请指教,因为我遇到了这个问题
  • @NareshSaxena:您应该使用 System.out.println(...) 调用来检查正在读入的字符串,检查它们是否有助于计数。换句话说——调试你的代码。
猜你喜欢
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 2021-12-23
  • 2019-08-19
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多