如何从.txt文件中读取2D数组?

时间:2012-04-06 13:54:49

标签: java stream io jtable multidimensional-array

我有这个.txt文件,其格式和内容如下(注意空格):

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

我想将它们存储到2D数组(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执行此操作吗?我更了解扫描仪。

1 个答案:

答案 0 :(得分: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) {...}
相关问题