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. 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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.