2012-04-06 64 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

相关问题