【问题标题】:How do I read a 2D array as it is from a .txt file?如何从 .t​​xt 文件中读取二维数组?
【发布时间】:2012-04-06 13:54:49
【问题描述】:

我有这个 .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 来执行此操作吗?我更了解扫描仪。

【问题讨论】:

  • 你不需要DataInputStream in = new DataInputStream(fi);。将FileInputStream 直接用于传递给BufferedReaderInputStreamReader
  • @Eng.Fouad 感谢您的提示。

标签: java stream io jtable multidimensional-array


【解决方案1】:

你需要的是这样的:

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 的转义字符,因此您需要对其进行转义,因此额外的\。加号只是表示 on 或 more of 的运算符。

第二次编辑:是的,您也可以使用 Scanner 来执行此操作,如下所示:

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

【讨论】:

  • 这是什么意思? “\\s+”?抱歉,我对 Java 很陌生。
  • @taeyeon:我修改了我的回复。希望对您有所帮助。
  • @Kevin:我想你的意思是:它匹配至少包含一个空格字符的字符串,而不是相反;)
  • @npinti 这真的很有帮助。但是,我在这一行得到了 ArrayOutOfBounds 异常:holder[lineCount][wordCount++] = segment; 我认为 wordCount 超出了持有人的长度。
  • @taeyeon:就像我说的,代码没有经过测试。最有可能的问题是需要交换阵列位置,即。使用holder[wordCount++][lineCount] = segment。代码应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2014-03-17
  • 1970-01-01
相关资源
最近更新 更多