How to add items to a JComboBox from an External File?
Please i need some help in adding items to a JComboBox in Java from an external file.
Here is my code so far:
//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开发者_JAVA技巧_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);
}
Mainly the format of my external file is as follows:
James|Robert|Alice
The names are separated by the "|" symbols.
My above code is adding only one element namely ("James") in this example. I need to add all three maybe in a loop or something. The idea is that i don't know for sure how many names will be in my external file. Thus using simple counters will not help.
Any suggestions are greatly appreciated!
Thanks in advance for your help
Try this:
StringTokenizer st = new StringTokenizer(str_Data); //Tokenizing the line.
while(st.hasMoreTokens()) {
cmb_Name.addItem(st.nextToken("|"));
}
精彩评论