2012-06-30 67 views
3

我開發了一個應用程序,用戶在其中選擇特定的文件夾,並將該文件夾中的所有java文件加上這些文件中單獨的代碼行並在控制檯中顯示,但在java項目中顯示有很多軟件包,現在我必須導航到特定的軟件包,我想修改應用程序,以便用戶選擇特定的項目時,他將進一步導航到只有src文件夾和src文件夾中的所有包含java文件包的代碼行將被計數。與Map相關的Java程序錯誤

public class abc { 

    /** 
    * @param args 
    * @throws FileNotFoundException 
    */ 
    private static int totalLineCount = 0; 
    private static int totalFileScannedCount = 0; 

    public static void main(String[] args) throws FileNotFoundException { 

     JFileChooser chooser = new JFileChooser(); 
     chooser.setCurrentDirectory(new java.io.File("C:" + File.separator)); 
     chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS"); 
     chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
     chooser.setAcceptAllFileFilterUsed(false); 
     if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
      Map<String, Integer> result = new HashMap<String, Integer>(); 
      File directory = new File(chooser.getSelectedFile().getAbsolutePath()); 

      List<File> files = getFileListing(directory); 

      //print out all file names, in the the order of File.compareTo() 
      for (File file : files) { 
       System.out.println("Directory: "+file); 
       result = getFileLineCount(file); 
       totalFileScannedCount += result.size(); 
      } 


      System.out.println("*****************************************"); 
      System.out.println("FILE NAME FOLLOWED BY LOC"); 
      System.out.println("*****************************************"); 

      for (Map.Entry<String, Integer> entry : result.entrySet()) { 
       System.out.println(entry.getKey() + " ==> " + entry.getValue()); 
      } 
      System.out.println("*****************************************"); 
      System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount); 
      System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount); 

     } 

    } 

    public static Map<String, Integer> getFileLineCount(File directory) throws FileNotFoundException { 
     Map<String, Integer> result = new HashMap<String, Integer>(); 

     File[] files = directory.listFiles(new FilenameFilter() { 

      @Override 
      public boolean accept(File directory, String name) { 
       if (name.endsWith(".java")) { 
        return true; 
       } else { 
        return false; 
       } 
      } 
     }); 
     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); 
        totalLineCount += lineCount; 
       } 
      } 
     } 

     return result; 
    } 

    /** 
    * Recursively walk a directory tree and return a List of all 
    * Files found; the List is sorted using File.compareTo(). 
    * 
    * @param aStartingDir is a valid directory, which can be read. 
    */ 
    static public List<File> getFileListing(
      File aStartingDir) throws FileNotFoundException { 
     validateDirectory(aStartingDir); 
     List<File> result = getFileListingNoSort(aStartingDir); 
     Collections.sort(result); 
     return result; 
    } 

    // PRIVATE // 
    static private List<File> getFileListingNoSort(
      File aStartingDir) throws FileNotFoundException { 
     List<File> result = new ArrayList<File>(); 
     File[] filesAndDirs = aStartingDir.listFiles(); 
     List<File> filesDirs = Arrays.asList(filesAndDirs); 
     for (File file : filesDirs) { 
      if(file.isDirectory()) { 
       result.add(file); 
      } 
      if (!file.isFile()) { 
       //must be a directory 
       //recursive call! 
       List<File> deeperList = getFileListingNoSort(file); 
       result.addAll(deeperList); 
      } 
     } 
     return result; 
    } 

    /** 
    * Directory is valid if it exists, does not represent a file, and can be read. 
    */ 
    static private void validateDirectory(
      File aDirectory) throws FileNotFoundException { 
     if (aDirectory == null) { 
      throw new IllegalArgumentException("Directory should not be null."); 
     } 
     if (!aDirectory.exists()) { 
      throw new FileNotFoundException("Directory does not exist: " + aDirectory); 
     } 
     if (!aDirectory.isDirectory()) { 
      throw new IllegalArgumentException("Is not a directory: " + aDirectory); 
     } 
     if (!aDirectory.canRead()) { 
      throw new IllegalArgumentException("Directory cannot be read: " + aDirectory); 
     } 
    } 
} 

現在的問題是這種方法的問題是,如果在一個名爲TestResult中的Java項目有3個包,每個包有2個文件的每個然後在控制檯上的結果也顯示文件名,然後只祿最新的軟件包只允許在一個Java projest說3包名爲ABC,DEF和TYU

com.abc package having files --->abc.java 
com.def package having files --->abc.java 
com.tyu package having files --->FileBrowse.java , FileCountLine.java 

the outcome shown in console is... 


    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\.settings 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\bin 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\src 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\src\com 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\src\com\abc 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\src\com\def 
    Directory: C:\Users\vaio\Desktop\Demo\TESTRESULT\src\tyu 
    ***************************************** 
    FILE NAME FOLLOWED BY LOC 
    ***************************************** 
    FileBrowse.java ==> 95 
    FileCountLine.java ==> 53 
    ***************************************** 
    SUM OF FILES SCANNED ==> 4 
    SUM OF ALL THE LINES ==> 296 

這是不完美的。請告知如何通過LOC顯示FILENAME所有文件

我認爲在讀取文件和行數的方法中,爲每個目錄創建一個NEW Map並將其重新分配給相同的結果。由於在重新分配地圖之前不顯示數據,因此以前的地圖不再可訪問,並且在您進入顯示屏時,您只有最後一個目錄的地圖。相反,您應該維護一個Map並將每個目錄的新值插入到相同的Map中。

public static void main(String[] args) throws FileNotFoundException { 
      //... 
      for (File file : files) { 
       System.out.println("Directory: "+file); 
       result = getFileLineCount(file); 

就在那裏,你從getFileLineCount()得到一個地圖返回,並將其分配給結果。這會丟棄先前創建的結果Map,並且會失去已經存在的所有內容。您有幾種選擇:

  1. 結果傳遞映射到getFileLineCount()方法,以便您可以添加結果到了一個地圖,而不是getFileLineCount()方法內爲每個文件夾創建一個新的地圖
  2. 採取從結果getLineCount()並將它們複製到結果地圖中而不是替換結果地圖
  3. 創建另一個集合,例如像地圖:Map<String, Map<String, Integer>>(它會將getFileLineCount()方法返回的結果映射到與結果有關的目錄名稱),或List<Map<String, Integer>>(這將是一個簡單的結果列表由getFileLineCount()返回,沒有任何映射到父目錄)。

請指教如何重構我的代碼,在此先感謝

回答

3

你可以做這樣的事情:

result.put(file, lineCount); 

代替

result.put(file.getName(), lineCount); 

當你打印出結果你可以打印漂亮的文件名。就像這樣:

for (Map.Entry<File, Integer> entry : result.entrySet()) { 
    System.out.println(entry.getKey().getName() + " ==> " + entry.getValue()); 
} 

當然地圖應該再聲明:Map.Entry<File, Integer>


當然,這可以改善了很多,但最小的變化,你可以有這樣的(這實際上是做什麼你預計,如果你不想要整個路徑,請更改打印名稱):

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FilenameFilter; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import java.util.NoSuchElementException; 
import java.util.Scanner; 

import javax.swing.JFileChooser; 

public class abc { 

    /** 
    * @param args 
    * @throws FileNotFoundException 
    */ 
    private static int totalLineCount = 0; 
    private static int totalFileScannedCount = 0; 

    public static void main(final String[] args) throws FileNotFoundException { 

     JFileChooser chooser = new JFileChooser(); 
     chooser.setCurrentDirectory(new java.io.File("C:" + File.separator)); 
     chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS"); 
     chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
     chooser.setAcceptAllFileFilterUsed(false); 
     if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
      Map<File, Integer> result = new HashMap<File, Integer>(); 
      File directory = new File(chooser.getSelectedFile().getAbsolutePath()); 

      List<File> files = getFileListing(directory); 

      // print out all file names, in the the order of File.compareTo() 
      for (File file : files) { 
       System.out.println("Directory: " + file); 
       getFileLineCount(result, file); 
      } 

      System.out.println("*****************************************"); 
      System.out.println("FILE NAME FOLLOWED BY LOC"); 
      System.out.println("*****************************************"); 

      for (Map.Entry<File, Integer> entry : result.entrySet()) { 
       System.out.println(entry.getKey().getAbsolutePath() + " ==> " + entry.getValue()); 
      } 
      System.out.println("*****************************************"); 
      System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount); 
      System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount); 
     } 

    } 

    public static void getFileLineCount(final Map<File, Integer> result, final File directory) 
      throws FileNotFoundException { 
     File[] files = directory.listFiles(new FilenameFilter() { 

      public boolean accept(final File directory, final String name) { 
       if (name.endsWith(".java")) { 
        return true; 
       } else { 
        return false; 
       } 
      } 
     }); 
     for (File file : files) { 
      if (file.isFile()) { 
       totalFileScannedCount++; 
       Scanner scanner = new Scanner(new FileReader(file)); 
       int lineCount = 0; 
       try { 
        for (lineCount = 0; scanner.nextLine() != null; lineCount++) { 
         ; 
        } 
       } catch (NoSuchElementException e) { 
        result.put(file, lineCount); 
        totalLineCount += lineCount; 
       } 
      } 
     } 

    } 

    /** 
    * Recursively walk a directory tree and return a List of all Files found; 
    * the List is sorted using File.compareTo(). 
    * 
    * @param aStartingDir 
    *   is a valid directory, which can be read. 
    */ 
    static public List<File> getFileListing(final File aStartingDir) throws FileNotFoundException { 
     validateDirectory(aStartingDir); 
     List<File> result = getFileListingNoSort(aStartingDir); 
     Collections.sort(result); 
     return result; 
    } 

    // PRIVATE // 
    static private List<File> getFileListingNoSort(final File aStartingDir) throws FileNotFoundException { 
     List<File> result = new ArrayList<File>(); 
     File[] filesAndDirs = aStartingDir.listFiles(); 
     List<File> filesDirs = Arrays.asList(filesAndDirs); 
     for (File file : filesDirs) { 
      if (file.isDirectory()) { 
       result.add(file); 
      } 
      if (!file.isFile()) { 
       // must be a directory 
       // recursive call! 
       List<File> deeperList = getFileListingNoSort(file); 
       result.addAll(deeperList); 
      } 
     } 
     return result; 
    } 

    /** 
    * Directory is valid if it exists, does not represent a file, and can be 
    * read. 
    */ 
    static private void validateDirectory(final File aDirectory) throws FileNotFoundException { 
     if (aDirectory == null) { 
      throw new IllegalArgumentException("Directory should not be null."); 
     } 
     if (!aDirectory.exists()) { 
      throw new FileNotFoundException("Directory does not exist: " + aDirectory); 
     } 
     if (!aDirectory.isDirectory()) { 
      throw new IllegalArgumentException("Is not a directory: " + aDirectory); 
     } 
     if (!aDirectory.canRead()) { 
      throw new IllegalArgumentException("Directory cannot be read: " + aDirectory); 
     } 
    } 
} 
+2

1+爲答案,10+爲閱讀整個問題。 –

+0

@Spaeth非常感謝您,請允許我以代碼的形式展示,因爲我已經完成了需要完成的更改,這將會非常有幫助 –

+0

@Spaeth您可以在我的上述代碼中進行更改,然後請填寫完整代碼,因爲我已經做了這將是一個很大的幫助,因爲我仍然困惑需要做什麼修改,請幫助 –