繁体   English   中英

如何从 .txt 文件中读取二维数组?

[英]How do I read a 2D array as it is from a .txt file?

我有以下格式和内容的 this.txt 文件(注意空格):

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

我想将它们存储到二维数组 ( holder[5][2] ) 中,同时将它们 output 存储到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来做到这一点吗? 我更了解扫描仪。

你需要的是这样的:

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) {...}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM