简体   繁体   中英

How to read multiple files one by one and display in the same text area in java swing?

I'm doing some coding for an assignment. I'm using java swing to do it. I need to know that how should change my code to display multiple files content in a text area.

I've tried some codes. I added one jButton and one jTextArea to read multiple files. I already know something about setMultiSelectionEnabled(true) and getSelectedFiles().

//This is my code inside the jButton

    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    chooser.showOpenDialog(null);
    File files = chooser.getSelectedFiles();
    String filename = files.getAbsolutePath();


    try{
       FileReader reader = new FileReader(filename);
       BufferedReader br = new BufferedReader(reader);
       jTextArea1.read(br, null);

       br.close();
       jTextArea1.requestFocus();
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

I can only get one file content into my text area yet. Please help me to develop this. Thank you!

If you want multiple files in a single text area, then you can't use the read(...) method.

Instead you will need to read each file line by line and the add the text to the text area using the append(...) method.

try this code:

  JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(true);
        chooser.showOpenDialog(null);
        File[] files = chooser.getSelectedFiles();
       // String filename = files.getAbsolutePath();



           for(File f:files){
           FileReader reader = new FileReader(f);
           BufferedReader br = new BufferedReader(reader);
           while( (line = br.readLine()) != null ) {
                jTextArea1.append(line);
           }

           br.close();
           //jTextArea1.requestFocus();
         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM