[英]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.