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 8159985
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T18:06:06+00:00 2026-06-06T18:06:06+00:00

I have developed a program that is counting the number of lines in a

  • 0

I have developed a program that is counting the number of lines in a file that is shown below

Scanner in=new Scanner(System.in);
    System.out.println("Enter the Drive name like C,D,E etc");
    String drive=in.next();
    System.out.println("Enter the main folder name");
    String main_folder=in.next();
    File directory=new File(drive+":"+"//"+main_folder+"//");

Map<String, Integer> result = new HashMap<String, Integer>();
    //File directory = new File("C:/Test/");
    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);
            } }}        

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

but I was trying to add a swing interface JFilechooser , I want that user should select the particular folder and all the files inside that folder to be get selected and rest above as my code works as it is , Please advise

Please advise for desiging the jfile chooser so that I can integrate my above code.

I have design one more solution that is

package aa;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class FileBrowse extends JFrame {

private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");


public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);

browseSwing.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource()==browseSwing)
        onBrowseSwing();
        }});


Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);

//pack();
}

protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}

public void fileRead(String input){
    try{
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream(input);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int count = 0;
        int count2 = 0;
        //Read File Line By Line
        while((strLine = br.readLine())!= null ){
            if (strLine.trim().length() != 0){
                count++;
            }else{
                count2++;
            }
        }
        System.out.println("-------Lines Of COdes-------");
        System.out.println("number of lines:" + count);
        System.out.println("number of blank lines:" + count2);
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }


}


public static void main(String[] args) {
new FileBrowse().setVisible(true);

}
}

but it chooses the individual files I want that all the files to be get selected inside that folder Test

  • 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-06T18:06:07+00:00Added an answer on June 6, 2026 at 6:06 pm

    You could use this code (adapted from here):

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("choosertitle");
        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(choosers.getSelectedFile().getAbsolutePath()); //This is where you need to change.
            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);
                    }
                }
            }
    
            for (Map.Entry<String, Integer> entry : result.entrySet())
            {
                System.out.println(entry.getKey() + " ==> " + entry.getValue());
            }
        }
    

    This code should replace this section:

    Scanner in=new Scanner(System.in);
    System.out.println("Enter the Drive name like C,D,E etc");
    String drive=in.next();
    System.out.println("Enter the main folder name");
    String main_folder=in.next();
    File directory=new File(drive+":"+"//"+main_folder+"//");
    

    Also, just a recommendation, when working with consoles and system paths, you should ideally use File.seperator. This will automatically provide you with the respective system’s path separation character.

    As per your edit, in your case you are using the fileChooser.getSelectedFile();. This will only get you the file that the user has selected, as per its name. What you should use is the fileChooser.getSelectedFile().getAbsolutePath() and iterate over the files which are within that same directory (as shown above).

    EDIT 2: I use this code to display 2 buttons with their respective event handlers:

    public static void main(String args[]) {
            JFrame frame = new JFrame("Button Sample");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JButton btnExit= new JButton("EXIT");    
    
            ActionListener actionListenerExitButton = new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Exit Button Was Clicked");
              }
            };
            btnExit.addActionListener(actionListenerExitButton);
    
            JButton btnEnter = new JButton("ENTER");
            ActionListener actionListenerEnterButton = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    System.out.println("Enter Button Was Clicked");
                }
            };
            btnEnter.addActionListener(actionListenerEnterButton);
    
            Container contentPane = frame.getContentPane();
            contentPane.add(btnExit, BorderLayout.SOUTH);
            contentPane.add(btnEnter, BorderLayout.NORTH);
            frame.setSize(300, 100);
            frame.setVisible(true);
          }
    

    All that you need to do now is to plug in the code I have provided earlier in the appropriate event handler.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have developed a Java program that will count the number of files in
I have a program that is developed in MVC 3 Razor Syntax but whenever
I have developed a java program that runs fine in Mac OS X (10.6.7).
I have a VB6 COM DLL that was developed on a WinXP 32bit system.
I have a complex issue at hand. I have developed a program that takes
I have developed a C# script that opens an XLS file, parses it and
I have a program that needs to be developed. For confidentiality, I will use
I have program that requires Python 3, but I develop Django and it uses
I develop a Python-based drawing program, Whyteboard . I have tools that the user
I have a program developed and it has a single entry point. A Try

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.