Java文件到二维数组 [英] Java file to 2D array

查看:51
本文介绍了Java文件到二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从.txt文件创建2D数组,其中.txt文件如下所示:

I'm trying to create a 2D array from a .txt file, where the .txt file looks something like this:

xxxx            
xxxx                 
xxxx                 
xxxx                

或类似的东西

xxx
xxx
xxx

所以我需要处理2D数组的多个大小(注意:每个2D数组并不总是等于x和y维度)。是否有初始化数组,或获得每行的字符/字母/数字和列数的方法?我不想使用一般性的声明,例如:

So I need to handle multiple sizes of a 2D array (Note: Each 2D array will not always be equal x and y dimensions). Is there anyway to initialize the array, or get the number of characters/letters/numbers per line and number of columns? I do not want to use a general statement, something like:

String[][] myArray = new Array[100][100];

然后使用文件编写器和扫描器类填充数组看起来像这样吗?

And then would filling the array using filewriter and scanner classes look like this?

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();
  }
}


推荐答案

您我看到有几种选择:


  1. 遍历文件两次,第一次获取数组参数,或者

  2. 对其进行一次迭代,但填写 List< List< SomeType>> 可能会将您的列表实例化为ArrayLists。后者将在短期和长期内为您提供更大的灵活性。

  3. (根据MadProgrammer)第三种选择是重新构建文件,以提供决策所需的元数据。

  1. Iterate through the file twice, the first time getting the array parameters, or
  2. Iterate through it once, but fill up a List<List<SomeType>> possibly instantiating your Lists as ArrayLists. The latter will give you much greater flexibility in the short and long run.
  3. (per MadProgrammer) The third option is to re-structure the file to provide the meta data required to make decisions about the size of the array.

例如,使用您的代码,

  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文件到二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆