0

我开发了一个程序来计算文件中的行数,如下所示

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

但我试图添加一个摇摆界面 JFilechooser ,我希望用户应该选择特定文件夹以及该文件夹内的所有文件都被选中并在上面休息,因为我的代码按原样工作,请告知

请建议设计 jfile 选择器,以便我可以集成上面的代码。

我设计了另一种解决方案

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

}
}

但它选择了我希望在该文件夹测试中选择所有文件的单个文件

4

1 回答 1

2

您可以使用此代码(改编自此处):

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

此代码应替换此部分:

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+"//");

此外,只是建议,在使用控制台和系统路径时,您最好使用File.seperator. 这将自动为您提供相应系统的路径分隔符。

根据您的编辑,在您的情况下,您使用的是fileChooser.getSelectedFile();. 这只会根据其名称为您提供用户选择的文件。您应该使用的是fileChooser.getSelectedFile().getAbsolutePath()并迭代同一目录中的文件(如上所示)。

编辑 2:我使用此代码显示 2 个按钮及其各自的事件处理程序:

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

您现在需要做的就是将我之前提供的代码插入到相应的事件处理程序中。

于 2012-06-28T06:18:14.593 回答