2012-04-06 44 views
0

我有以下的格式和內容(請注意空格)此.txt文件:我如何讀一個二維數組,因爲它是從一個txt文件?

Apples 00:00:34 
Jessica 00:01:34 
Cassadee 00:00:20 

我想將它們存儲到一個二維數組(holder[5][2]),並在同一時間將其輸出到JTable。我已經知道如何在java中編寫和讀取文件,並將讀取的文件放入數組中。然而,當我使用此代碼:

try { 

     FileInputStream fi = new FileInputStream(file); 
     DataInputStream in = new DataInputStream(fi); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

     String line = null; 
     while((line = br.readLine()) != null){ 
      for(int i = 0; i < holder.length; i++){ 
       for(int j = 0; j < holder[i].length; j++){ 
        holder[i][j] = line; 
       } 
      } 
     } 

     in.close(); 


     } catch(Exception ex) { 
      ex.printStackTrace(); 
     } 

holder[][]陣列不輸出非常還有一個JTable:|請幫助?感謝誰能幫助我!

編輯:也就是可以用Scanner做到這一點?我更瞭解掃描儀。

+0

你不需要在=新DataInputStream類(FI)'DataInputStream類;'。直接使用'FileInputStream'到'InputStreamReader'這是傳遞給'BufferedReader'。 – 2012-04-06 13:59:29

+0

@ Eng.Fouad感謝您的提示。 – alicedimarco 2012-04-06 14:01:48

回答

2

你所需要的是這樣的:

int lineCount = 0; 
int wordCount = 0; 
String line = null; 
     while((line = br.readLine()) != null){ 
      String[] word = line.split("\\s+"); 
      for(String segment : word) 
      { 
       holder[lineCount][wordCount++] = segment;      
      } 
      lineCount++; 
      wordCount = 0; //I think now it should work, before I forgot to reset the count. 
     } 

請注意,此代碼是未經測試,但它應該給你的總體思路。

編輯:\\s+是正則表達式,其用於表示一個或多個空格字符,可以是一個空格或標籤。技術上,正則表達式是簡單\s+,但我們需要添加一個額外的空間,因爲\是一個轉義字符的Java,所以你需要逃避它,從而額外\。加號只是表示一個或多個的運算符。

第二個編輯:是的,你可以用Scanner做到這一點也像這樣:

Scanner input = new Scanner(new File(...)); 
while ((line = input.next()) != null) {...} 
+0

這是什麼意思? 「\\ S +」?對不起,我對Java很新。 – alicedimarco 2012-04-06 14:03:35

+0

@taeyeon:我修改了我的回覆。希望能幫助到你。 – npinti 2012-04-06 14:12:38

+1

@Kevin:我認爲你的意思是:它匹配至少包含一個空格字符的字符串,而不是其他方式;) – npinti 2012-04-06 14:13:23

相關問題