2011-03-06 84 views
0

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

任何建议,非常感谢!

在此先感谢您的帮助

回答

1

试试这个:

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

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