本文介绍了JFileChooser打开多个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JFileChooser打开两个文本文件,在我选择这些文件后,我想比较它们,在屏幕上显示等等。这可能吗?

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?

推荐答案

您可以让 JFileChooser 选择多个文件并返回一个File对象数组而不是一个

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

方法 showOpenDialog(frame)仅返回一旦你点击确定按钮

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

编辑

所以这样做:

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

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

这篇关于JFileChooser打开多个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 01:00