【问题标题】:reading file line by line and adding lines to array逐行读取文件并将行添加到数组
【发布时间】:2017-05-05 15:11:53
【问题描述】:

我想在 Java 中逐行读取文件。每行都作为一个项目添加到数组中。问题是,我必须在逐行读取时根据文件中的行数创建数组。

我可以使用两个单独的 while 循环,一个用于计数,然后创建数组,然后添加项目。但是对于大文件效率不高。

try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) {
  String line = "";
  int maxRows = 0;
  while ((line = br.readLine()) != null) {
    String [] str = line.split(" ");
    maxColumns = str.length;
    theRows[ maxRows ] = new OneRow( maxColumns );   // ERROR
    theRows[ maxRows ].add( str );
    ++maxRows;
  }
}
catch (FileNotFoundException e) {
  System.out.println(e.getMessage());
}
catch (IOException e) {
  System.out.println(e.getMessage());
}

考虑private OneRow [] theRows;OneRow 定义为String []。文件看起来像

Item1    Item2   Item3   ...
2,3       4n     2.2n
3,21      AF     AF
...

【问题讨论】:

标签: java arrays file


【解决方案1】:

您无法调整数组的大小。请改用ArrayList 类:

private ArrayList<OneRow> theRows;

...

theRows.add(new OneRow(maxColumns));

【讨论】:

  • 它为theRows 添加了什么?我要加str
  • 我想将String [] 添加到theRows。你的意思是private ArrayList&lt;OneRow []&gt; theRows;
  • 如果没有初始分配,这将引发 NPE
  • @mahmood 它添加了OneRow 对象,就像在您的原始代码中一样。
【解决方案2】:

检查ArrayList。 ArrayList 是可变数组,相当于 C++ Vector。

try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) 
{ 
    List<String> str= new ArrayList<>();
    String line = ""; 
    while ((line = br.readLine()) != null) { 
    str.add(line.split(" "));
    } 
} 
catch (FileNotFoundException e) { 
 System.out.println(e.getMessage());
} catch (IOException e){ 
 System.out.println(e.getMessage()); 
}

【讨论】:

  • @mahmood 那是因为它是List&lt;String&gt; 而不是List&lt;String[]&gt;。无论如何,不要使用第二个。如果你想要一个二维数组,请使用List&lt;List&lt;String&gt;&gt;
  • 为什么要制作数组的ArrayList?
  • 所以,你的str实际上是我的theRows。对吗?
  • 我的str就像你的数组str
  • 这两项之间是表格还是只有一个空格?
【解决方案3】:

我会考虑使用ArrayList 数据结构。如果您不熟悉 ArrayLists 的工作原理,我会阅读文档。

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 2021-04-08
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多