[英]File content into a jList
谁能向我解释如何将文本文件的内容加载到jList中? 我设法在控制台上打印了文件的内容。 我已经完成了Read()函数(逐行读取文件的内容)和Load()函数,该函数应该通过调用函数Read()在jList中显示内容。
加载代码:
public void Load()
{
Read();
File archive = null;
FileReader fr = null;
BufferedReader br = null;
try {
archive = new File ("Cars.txt");
fr = new FileReader (archive);
br = new BufferedReader(fr);
Vector<String> lines = new Vector<String>();
String line;
while((line=br.readLine())!=null) {
System.out.println(line);
lines.add(line);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try{
if( null != fr ) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
读取的代码:
public void Read()
{
String name , type , distance, time;
File file=new File("Cars.txt");
FileInputStream fis=null;
BufferedInputStream bis=null;
DataInputStream dis=null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0)
{
String x=dis.readLine();
int k1=x.length();
char []m=x.toCharArray();
int y1=0, y2=0, z=1;
for(int i=1;i<k1;i++)
if(m[i]==' ' && z==1)
{
y1=i;
z++;
}
else if(z==2 && m[i]==' ') {y2=i; z++; }
k1-=y2;
name=x.copyValueOf(x.toCharArray(), 0, y1);
type=x.copyValueOf(x.toCharArray(), 0, y2);
distance=x.copyValueOf(x.toCharArray(), y1+1, y2-y1-1);
time=x.copyValueOf(x.toCharArray(), y2+1, k1-1);
int d=Nr(distance);
int t=Nr(time);
// System.out.println(name + " " +q + " " + n);
list.Add(name, type , d, t);
}
fis.close();
bis.close();
dis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
创建如下列表:
DefaultListModel model = new DefaultListModel();
JList list = new JList( model );
然后,当您读取每一行数据时,可以使用:
model.addElement(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.