如何从外部文件添加项目到JComboBox?

时间:2011-03-06 20:02:11

标签: java file-io io text-processing jcombobox

在从外部文件添加项目到 JComboBox in Java 时,我需要一些帮助。

到目前为止,这是我的代码:

 //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”)。我需要在循环或其他东西中添加所有三个。我的想法是,我不确定我的外部文件中会有多少名字。因此使用简单的计数器将无济于事。

非常感谢任何建议!

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

试试这个:

   StringTokenizer st = new StringTokenizer(str_Data); //Tokenizing the line.

   while(st.hasMoreTokens()) {
        cmb_Name.addItem(st.nextToken("|"));
   }