来自文本文件的java 2D数组

时间:2014-10-30 01:20:38

标签: java arrays eclipse multidimensional-array stringtokenizer

我正在尝试将此input.txt转换为2D数组。我尝试了几种不同的方法。这是我最近的尝试,我似乎被困在这里......任何帮助都非常感谢。

input.txt结构:SCI2000 / Science / 1200/10 / C - >有23行和5列。我还想为每一栏制作一个标题。

    FileReader fr = new FileReader("input.txt");
    BufferedReader br = new BufferedReader(fr);
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
    String[][] input = new String[23][5];
    String[] tokens = everything.split("/");
    for(String str : tokens)
        System.out.print(str);

2 个答案:

答案 0 :(得分:0)

只是主要处理部分(未经测试):

int columns = 5; 
String[] row = String[columns];
int j = 0; 

while ((line = br.readline) != null) {
    row = line.split("/");
    for(int i=0; i<row.length; ++i) {
       input[j,i] = row(i);
    }
    ++j;
}

答案 1 :(得分:0)

FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
String[][] input = new String[24][5]; // 1 row for title, 23 rows for data

// add title
input[0] = new String[]{"title1", "title1", "title1", "title1", "title1"};
String line = br.readLine();
int row = 1; // update here

while ( (line = br.readLine())!= null ) {
    input[row++] = line.split("/");
}

// print all data
for ( int i = 0; i < input.length; i++) {
    for ( int j = 0; j < input[i].length; j++ )
        System.out.print(input[i][j] + " ");

    //new line
    System.out.println();
}