Reputation: 23
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!
Upvotes: 2
Views: 946
Reputation: 129
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();
}
Upvotes: 0
Reputation: 324098
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.
Upvotes: 2