[英]Counting the number of lines in a file
I am trying to develop a program in java that will count the number of files in a given folder along with the lines of code in each individual file. 我正在尝试用Java开发一个程序,该程序将计算给定文件夹中文件的数量以及每个单独文件中的代码行。 I currently have code that will only pick up a single file from the folder and count the lines of code for that particular file.
我目前有一些代码,这些代码只能从文件夹中提取一个文件,并计算该特定文件的代码行数。 Please help me understand how to proceed from here.
请帮助我了解如何从此处继续。
My current code: 我当前的代码:
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);
}
}
Use 采用
String dir ="/home/directory";
File[] dirContents = dir.listFiles();
List out each files and apply your code on each of them. 列出每个文件,然后将代码应用于每个文件。 Store the filename and line count in a Map.
将文件名和行数存储在地图中。
The idea of @Akhil, implemented: @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.