【发布时间】:2011-03-06 20:02:10
【问题描述】:
在从外部文件向 Java 中的 JComboBox 添加项目时,我需要一些帮助。
这是我目前的代码:
//Loading the Names:
File Names_File = new File("Data" + File.separator + "Names.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String str_Data = ""; //For storing the input from the file.
try
{
fis = new FileInputStream(Names_File);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
str_Data = dis.readLine(); //Reading the line from the file.
StringTokenizer st = new StringTokenizer(str_Data); //Tokenizing the line.
//The below line adds only one item. The objective is adding all the items.
//*** Requesting help here ***
cmb_Name.addItem(st.nextToken("|"));
//*** Requesting help here ***
// Disposing and closing all the resources after using them.
fis.close();
bis.close();
dis.close();
}
catch (FileNotFoundException e)
{
System.err.println("Error: File not found!");
JOptionPane.showMessageDialog(null, "Error: File not found!", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
catch (IOException e)
{
System.err.println("Error: Unable to read from file!");
JOptionPane.showMessageDialog(null, "Error: Unable to read from file!", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
主要是我的外部文件格式如下:
詹姆斯|罗伯特|爱丽丝
名称由 "|" 符号分隔。
我上面的代码在这个例子中只添加了一个元素,即 ("James")。我需要添加所有三个可能在一个循环或什么的。这个想法是我不确定我的外部文件中有多少个名字。因此,使用简单的计数器将无济于事。
非常感谢任何建议!
提前感谢您的帮助
【问题讨论】:
标签: java file-io io text-processing jcombobox