2013-01-24 83 views
2

我想讀一個.txt文件的內容,而我想表明它在JTextAreas的數量在我的GUI閱讀txt文件的內容,並顯示在多個文本區域

我的文本文件的內容8張隨機數與逗號彼此分開它們(如以下)

200,140,​​300,30,30,70,70,20

我有我的GUI 8的JTextArea,我想表現出不同的JTextArea每個號碼。

那麼如何在文本文件中使用逗號(,)作爲分隔符?

以下代碼完美打開文件,但它僅在一個文本區域中顯示所選.txt文件的內容。我如何編輯我的代碼以實現目標?

b2.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 

      JFileChooser fc = new JFileChooser(); 
      int returnVal = fc.showOpenDialog(fc); 
      if (returnVal == JFileChooser.APPROVE_OPTION) 
      { 
        File file = fc.getSelectedFile(); 
        try 
        { 
        FileReader fr = new FileReader(file); 
        o = new BufferedReader(fr); 
        while((s=o.readLine())!=null) 
         t1.setText(s); 
        } 
        catch (FileNotFoundException e) 
        { 
        e.printStackTrace(); 
        } 
        catch (IOException e) 
        { 
        e.printStackTrace(); 
        }     
      } 
     } 
    }); 
+2

不要忘記調用'fr.close()'的'finally' -塊。 – MrSmith42

+0

@ MrSmith42感謝提醒! –

回答

4

您必須標記指定「,」作爲分隔符的文本文件的內容。

String content = "200, 140, 300, 30, 30, 70, 70, 20; 
String[] tokens = content.split(", "); 

之後,您可以訪問令牌數組中的每個數字。

+0

工作!謝謝 –

2

您可以通過使用s.split拆分此數字( 「」)

試試這個

 FileReader fr = new FileReader(file); 
     BufferedReader o = new BufferedReader(fr); 
     String s; 
     while ((s = o.readLine()) != null) { 
      String Values[] = s.split(","); 
      for (int i = 0; i < Values.length; i++) { 
       System.out.println(Values[i]);//////////here You can set JTextArea by using Values[i] 

      } 
     }