java - 从 txt 读取二维数组列表
问题描述
我有这个二维数组列表,我想使用 buffer Reader(Java) 从我的 txt 文件中读取它。有什么帮助吗?
//我的二维数组列表,整数 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 - 程序不断终止,我不知道为什么
- git - 获取文件在 repo 中完全匹配时的所有提交哈希
- flutter - 如何在 Flutter 中使用 ImagePicker 打开手机图库或相机或任何其他可用的媒体。
- shopify - Liquid - 了解“where”的使用
- flutter - 颤动中的重绘边界寿命
- docker - standard_init_linux.go:211:exec 用户进程在将 shell 脚本复制到容器时导致“没有这样的文件或目录”
- c# - 将 tiff 文件转换为 pdf 时出现 C# 内存不足异常
- bash - 如何grep版本的apache?
- node.js - 在天蓝色上部署反应应用程序后出现错误
- javascript - Luxon 区间人类可读