2

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

    }

} 
4

2 回答 2

5

利用

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

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

于 2012-06-27T11:23:24.143 回答
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);
于 2012-06-27T11:37:24.780 回答