[英]Java file to 2D array
我正在尝试从.txt文件创建2D数组,其中.txt文件看起来像这样:
xxxx
xxxx
xxxx
xxxx
或类似这样的东西:
xxx
xxx
xxx
因此,我需要处理2D数组的多个大小(注意:每个2D数组并不总是等于x和y尺寸)。 是否有初始化数组,或获得每行的字符/字母/数字和列数的方法? 我不想使用一般性声明,例如:
String[][] myArray = new Array[100][100];
然后使用Filewriter和Scanner类填充数组看起来像这样吗?
File f = new File(filename);
Scanner input = new Scanner(f);
for(int i = 0; i < myArray[0][].length; i++){
for(int j = 0; j < myArray[][0].length, j++){
myArray[i][j] = input.nextLine();
}
}
在我看来,您有几种选择:
List<List<SomeType>>
可能List<List<SomeType>>
您的列表实例化为ArrayLists。 后者将在短期和长期内为您提供更大的灵活性。 例如,使用您的代码,
File f = new File(filename);
Scanner input = new Scanner(f);
List<List<String>> nestedLists = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<String> innerList = new ArrayList<>();
Scanner innerScanner = new Scanner(line);
while (innerScanner.hasNext()) {
innerList.add(innerScanner.next());
}
nestedLists.add(innerList);
innerScanner.close();
}
input.close();
Java Matrix可以根据您的大小要求设置每一行(这是一个数组)。
您可以使用: ArrayUtils.add(char[] array, char element) //static method
但在此之前,您需要检查文件行长度
要么,您还可以使用ArrayList>作为保存数据的集合
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.