繁体   English   中英

计算文件中的行数

[英]Counting the number of lines in a file

我正在尝试用Java开发一个程序,该程序将计算给定文件夹中文件的数量以及每个单独文件中的代码行。 我目前有一些代码,这些代码只能从文件夹中提取一个文件,并计算该特定文件的代码行数。 请帮助我了解如何从此处继续。

我当前的代码:

public class FileCountLine {

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

        File file = new File("E:/WalgreensRewardsPosLogSupport.java"); 
        Scanner scanner = new Scanner(file);    
        int count = 0;               
        while (scanner.hasNextLine()) { 
            String line = scanner.nextLine();   
        count++;              
        }           
        System.out.println("Lines in the file: " + count);

    }

} 

采用

String dir ="/home/directory";
File[] dirContents = dir.listFiles();

列出每个文件,然后将代码应用于每个文件。 将文件名和行数存储在地图中。

@Akhil的想法实现了:

Map<String, Integer> result = new HashMap<String, Integer>();

File directory = new File("E:/");
File[] files = directory.listFiles();
for (File file : files) {
    if (file.isFile()) {
        Scanner scanner = new Scanner(new FileReader(file));
        int lineCount = 0;
        try {
            for (lineCount = 0; scanner.nextLine() != null; lineCount++);
        } catch (NoSuchElementException e) {
            result.put(file.getName(), lineCount);
        }

    }
}

System.out.println(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM