JFileChooser to open multiple txt files

安稳与你 提交于 2019-11-29 05:34:50

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

You can use:

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);

// Show the dialog; wait until dialog is closed
chooser.showOpenDialog(frame);

// Retrieve the selected files.
File[] files = chooser.getSelectedFiles();

You can then use the file handles returned to do the compare.

In my case I solved it declaring frame as an initialized local variable set to null:

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);

Component frame = null;

chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!