2012-06-27 189 views
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); 

    } 

} 
+0

所以,你要爲它的行數的文件夾中的每個文件,對不對? – sp00m

回答

5

使用

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

列出每個文件和應用對他們每個人的代碼。將文件名和行數存儲在地圖中。

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);