Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser to open multiple txt files

Tags:

How can I use JFileChooser to open two text files and after I selected these files, I want to compare them, show on the screen etc. Is this possible?

like image 249
zenx Avatar asked Aug 12 '12 12:08

zenx


People also ask

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.

What is the main purpose of using JFileChooser?

As you have seen, the JFileChooser class provides the showOpenDialog method for displaying an open dialog and the showSaveDialog method for displaying a save dialog. The class has another method, showDialog , for displaying a file chooser for a custom task in a dialog.

How do I get files from JFileChooser?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).


1 Answers

You can have your JFileChooser select multiple files and return an array of File objects instead of one

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();

The method showOpenDialog(frame) only returns once you click the ok button

EDIT

So do this:

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();
if(files.length >= 2) {
    compare(readFileAsList(files[0]), readFileAsList(files[1]));
}

And change your readFileAsList to:

private static List<String> readFileAsList(File file) throws IOException {
    final List<String> ret = new ArrayList<String>();
    final BufferedReader br = new BufferedReader(new FileReader(file));
    try {
        String strLine;
        while ((strLine = br.readLine()) != null) {
            ret.add(strLine);
        }
        return ret;
    } finally {
        br.close();
    }
}
like image 98
La bla bla Avatar answered Sep 17 '22 15:09

La bla bla