Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

java - JFileChooser to open multiple txt files

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...