0

我开发了一个应用程序,用户在其中选择特定文件夹,它计算该文件夹中的所有 java 文件以及这些文件中单独的代码行并显示在控制台中,但是在 java 项目中,有很多包,现在我有导航到一个特定的包,我想修改应用程序,当用户选择特定项目时,他将进一步导航到仅 src 文件夹,并且从 src 文件夹中所有包含 java 文件行的包都将被计算在内.

请告知如何实现这一点..以下是我的一段代码:

public class abc {


    /**
     * @param args
     * @throws FileNotFoundException
     */
    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()); 
             int totalLineCount = 0;
             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;  
                                    }


                } }
              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"+result.size()); 
            System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);

             }     

    }

}

现在我的代码的问题是,当我启动我的应用程序时,会打开一个对话框,我必须在其中浏览到最终包含 java 文件的完整包文件夹,但现在我想以这样的方式修改应用程序,以便当文件对话框打开,用户将仅导航到项目 src 文件夹,从那时起需要扫描 src 文件夹内的所有包和所有文件行代码,请告知..

我当时在想的是...

  • 给定一个代表目录的文件对象(我们称之为目录):
  • 获取目录中的所有文件。
  • 对于目录中的每个文件,(我们将其称为 thisFile)执行以下操作:
  • 如果 thisFile 是目录,则从头开始使用 thisFile 作为目录
  • 否则,如果 thisFile 是 .java 文件,请计算代码行数
  • 否则,忽略此文件

如果将 main 分成方法,这会变得容易得多。

4

1 回答 1

0

代码在这里

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(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);
        }
    }
}
于 2012-06-30T05:29:50.947 回答