我有这个二维数组列表,我想从我的 txt 文件中读取它 使用缓冲区读取器(Java)。有什么帮助吗?
//我的带有整数的二维数组列表 1 2 3 4 5 6 7 8 9 10 11 12
最佳答案
您的输入是一维数组,因此要将其读取为二维数组 - 您必须提供(或从某处获取)生成的二维数组的宽度和/或高度。
这里是示例:
// 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!
关于java - 从 txt 读取二维数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59415192/