I have the following Java code to read a txt file:
class ReadFile {
public static void main(String [] args) {
File archivo = null;
FileReader fr = null;
BufferedReader br = null;
try {
archivo = new File ("C:\\archivo.txt");
fr = new FileReader (archivo);
br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null)
System.out.println(line);
}
catch(Exception e){
e.printStackTrace();
}finally{
try{
if( null != fr ){
fr.close();
开发者_高级运维 }
}catch (Exception e2){
e2.printStackTrace();
}
}
}
But I need to load that info into a JList
, so this JList
would show me what words I have saved in the file. Does anyone knows how to do that?
Source
import java.io.*;
import javax.swing.*;
import java.util.Vector;
class ReadFile {
public static void main(String [] args) {
File archivo = null;
FileReader fr = null;
BufferedReader br = null;
try {
archivo = new File ("ReadFile.java");
fr = new FileReader (archivo);
br = new BufferedReader(fr);
// normally I would prefer to use an ArrayList, but JList
// has a constructor that takes a Vector directly.
Vector<String> lines = new Vector<String>();
String line;
while((line=br.readLine())!=null) {
System.out.println(line);
lines.add(line);
}
JOptionPane.showMessageDialog(null, new JScrollPane(new JList(lines)));
} catch(Exception e) {
e.printStackTrace();
} finally {
try{
if( null != fr ) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
精彩评论