Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8166969
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T20:03:44+00:00 2026-06-06T20:03:44+00:00

I have developed a application in which user select the particular folder and it

  • 0

I have developed a application in which user select the particular folder and it counts all the java files in that folder plus the line of code individually in those files and show at console but in a java project there are so many packages and right now I have to navigate until a particular package , I want to modify the application in such a way that when user select the particular project, he will then further navigate to only src folder and from src folder all the packages containing java files line of code will be counted.

Please advise how to achieve that..below is my piece of code:

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

             }     

    }

}

the problem with my code is now when I start my application an dialog box get opened in which I have to browse till the complete package folder which finally contains the java files but now I want to modify the application in such a way so that when file diaolog box get opened , user will navigate to project src folder only and from then onwards all the packages inside the src folder need to be scanned and all the files line of code,please advise..

What I was thinking was…

  • Given a File Object that represents a directory (we will call it Directory):
  • Get all the Files in the Directory.
  • For Each File in the Directory, (we will call it thisFile) do the following:
  • If thisFile is a directory, start from the beginning use thisFile as the Directory
  • Else, If thisFile is a .java file, count the lines of code
  • Else, ignore thisFile

This gets a whole lot easier if you separate the main into methods.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T20:03:45+00:00Added an answer on June 6, 2026 at 8:03 pm

    Here the code goes

    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);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have developed a application in which user select the particular folder and it
Hai I have developed a standalone application in which when an user logs in,
I have developed a java application which run's perfectly in local server. But When
We have developed a web application which consumes a web service. The user will
I have developed an application which can create Xml files from Xml schema with
I have developed web application which uses JasperReports for reporting purpose. In that I
I have developed a web based application which allows a client/user to upload a
I have developed a grails/groovy application for a legacy database which has user maintenance
I have developed one application in which i have to detect whether user has
I have developed an application which allows the user to switch between themes. I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.