Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要使用java内置方法删除空白吗_Java_String_Io - Fatal编程技术网

要使用java内置方法删除空白吗

要使用java内置方法删除空白吗,java,string,io,Java,String,Io,我开发了一个应用程序,可以读取java项目中一个java包中有多少个文件,并计算这些文件中的代码行,例如在一个java项目中,如果有两个包中有4个单独的文件,那么读取的文件总数将为4,如果这4个文件中每个文件中有10行代码然后4*10是整个项目中总共40行代码…下面是我的代码 private static int totalLineCount = 0; private static int totalFileScannedCount = 0; publ

我开发了一个应用程序,可以读取java项目中一个java包中有多少个文件,并计算这些文件中的代码行,例如在一个java项目中,如果有两个包中有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);
            }
        }
private static int totalinecount=0;
私有静态int totalFileScannedCount=0;
公共静态void main(最终字符串[]args)引发FileNotFoundException{
JFileChooser chooser=新的JFileChooser();
setCurrentDirectory(新的java.io.File(“C:+File.separator”);
setDialogTitle(“带行号的文件”);
setFileSelectionMode(仅限于JFileChooser.DIRECTORIES_);
选择器.setAcceptableFileFilterUsed(false);
if(chooser.showOpenDialog(null)=JFileChooser.APPROVE\u选项){
映射结果=新的HashMap();
文件目录=新文件(chooser.getSelectedFile().getAbsolutePath());
List files=getFileListing(目录);
//按file.compareTo()的顺序打印所有文件名
用于(文件:文件){
//System.out.println(“目录:+文件);
getFileLineCount(结果、文件);
//totalFileScannedCount+=result.size();//saral
}
System.out.println(“**********************************************************”);
System.out.println(“文件名后跟LOC”);
System.out.println(“**********************************************************”);
for(Map.Entry:result.entrySet()){
System.out.println(entry.getKey().getAbsolutePath()+“==>”+entry.getValue());
}
System.out.println(“**********************************************************”);
System.out.println(“扫描的文件总数==>”+“\t”+totalFileScannedCount);
System.out.println(“所有行的总和==>”+“\t”+TotalineCount);
}
}
公共静态void getFileLineCount(最终映射结果,最终文件目录)
抛出FileNotFoundException{
File[]files=directory.listFiles(新文件名过滤器(){
公共布尔接受(最终文件目录、最终字符串名称){
if(name.endsWith(“.java”)){
返回true;
}否则{
返回false;
}
}
});
用于(文件:文件){
if(file.isFile()){
Scanner Scanner=新扫描仪(新文件读取器(文件));
int lineCount=0;
totalFileScannedCount++;//saral
试一试{
对于(lineCount=0;scanner.nextLine()!=null;){
while(scanner.hasNextLine()){
字符串行=scanner.nextLine().trim();
如果(!line.isEmpty()){
lineCount++;
}
}
}捕获(无接触元素例外e){
结果.put(文件、行数);
TotalineCount+=行数;
}
}
}
}
/**
*递归遍历目录树并返回找到的所有文件的列表;
*使用File.compareTo()对列表进行排序。
* 
*@param aStartingDir
*是可以读取的有效目录。
*/
静态公共列表getFileListing(最终文件aStartingDir)引发FileNotFoundException{
validateDirectory(aStartingDir);
列表结果=getFileListingNoSort(aStartingDir);
集合。排序(结果);
返回结果;
}
//私人的//
静态私有列表getFileListingNoSort(最终文件aStartingDir)引发FileNotFoundException{
列表结果=新建ArrayList();
File[]filesAndDirs=aStartingDir.listFiles();
List filesDirs=Arrays.asList(filesAndDirs);
for(文件:filesDirs){
if(file.isDirectory()){
结果.添加(文件);
}
如果(!file.isFile()){
//必须是一个目录
//递归调用!
List deeperList=getFileListingNoSort(文件);
结果:addAll(deeperList);
}
}
返回结果;
}
/**
*目录是有效的,如果它存在,不代表文件,并且可以
*阅读。
*/
静态私有void validateDirectory(最终文件addirectory)引发FileNotFoundException{
if(aDirectory==null){
抛出新的IllegalArgumentException(“目录不应为null”);
}
如果(!aDirectory.exists()){
抛出新的FileNotFoundException(“目录不存在:“+A目录”);
}
如果(!aDirectory.isDirectory()){
抛出新的IllegalArgumentException(“不是目录:“+a目录”);
}
如果(!aDirectory.canRead()){
抛出新的IllegalArgumentException(“无法读取目录:“+A目录”);
}
}
但问题是,在计算单个文件的代码行时,它也会计算空白行,这是不应该的。请告知我需要在我的程序中进行哪些修改,以便在计算单个文件的代码行时,它不会计算空白行

我心中的想法
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++;
   }
}