计算文件中的行数

时间:2012-06-27 11:21:11

标签: java

我正在尝试在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);

    }

} 

2 个答案:

答案 0 :(得分:5)

使用

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

列出每个文件并在每个文件上应用您的代码。将文件名和行数存储在Map中。

答案 1 :(得分:0)

@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);
相关问题