想要使用java内置方法删除空格 [英] Want to remove the whitespaces, with java built in methods

查看:149
本文介绍了想要使用java内置方法删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have developed an application that read how many files are there in a java package inside the java project and count the line of code in those individual files to for example in a java project if there are 2 packages having 4 individual files then total files read will be 4 and if those 4 files having 10 piece of lines of code in each file then 4*10 is total 40 lines of code in overall project ...below is my piece of code

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

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

but the issue is that it also count the white space lines while calculating the line of code for the individual files , which it should not , please advise what modifications I need to do in my program so that it should not count the white spaces while calculating the line of code for the individual files .

我想到的想法只是将读取的字符串与进行比较,并计算如果不等于(空),如if(!readString.trim( ).equals())lineCount ++
请指教这个

The idea that was coming to my mind was just compares the read string with "", and count if not equals to "" (empty) like if(!readString.trim().equals("")) lineCount++ Please advise for this

推荐答案

建议:


  • 扫描仪有一个 hasNextLine()方法,你应该使用它。我会将它用作while循环的条件。

  • 然后通过调用 nextLine()获取while循环内的行一旦进入循环内部。

  • 再次在读入的字符串上调用 trim()。我仍然看不到你的在最新的代码更新中尝试此操作!

  • 在Strings上调用方法时的一个关键概念是它们是不可变的,并且调用它们的方法不会更改底层String,并且 trim()没有什么不同:调用它的字符串没有变化,但 方法改变了字符串返回,事实上是修剪。

  • String有一个 isEmpty()方法,你应该在修剪字符串后调用它。

  • Scanner has a hasNextLine() method which you should use. I would use it as the condition of a while loop.
  • Then get the line inside the while loop by calling nextLine() just once inside of the loop.
  • Again call trim() on your Strings that are read in. I still don't see your attempt at this in the latest code update!
  • A key concept when calling methods on Strings is that they are immutable, and the methods called on them do not change the underlying String, and trim() is no different: The String that it is called on is unchanged, but the String returned by the method is changed, and in fact is trimmed.
  • String has an isEmpty() method that you should call after trimming the 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++;
   }
}

这篇关于想要使用java内置方法删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆