首页 > 解决方案 > 从 txt 读取二维数组列表

问题描述

我有这个二维数组列表,我想使用 buffer Reader(Java) 从我的 txt 文件中读取它。有什么帮助吗?

//我的二维数组列表,整数 1 2 3 4 5 6 7 8 9 10 11 12

标签: javamultidimensional-arrayintegerreaderbuffered

解决方案


您的输入是一维数组,因此要将其读取为二维数组 - 您必须提供(或从某处获取)生成的二维数组的宽度和/或高度。

这是示例:

// Prepare memory for the output
int width=4;
int height=3;

int[][] d2 = new int[height][width];

try {
    BufferedReader br = new BufferedReader(new FileReader("test.txt"));
    String fileContent = "";
    String line;

    while ((line = br.readLine()) != null) {
      fileContent += line + " ";
    }

    String ints[] = fileContent.split("\\p{javaWhitespace}+");

    for(int i=0;i<height;i++) {
      for (int j = 0; j < width; j++) {
        if((i * width + j) >= ints.length) throw new RuntimeException("Not enough ints :-(");
        d2[i][j] = Integer.parseInt(ints[i * width + j]);
      }
    }
} catch (Exception e) {
  e.printStackTrace();
}

/// Now you have the 2d_array in d2!

推荐阅读