Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 逐行读取文件并向数组中添加行_Java_Arrays_File - Fatal编程技术网

Java 逐行读取文件并向数组中添加行

Java 逐行读取文件并向数组中添加行,java,arrays,file,Java,Arrays,File,我想用Java逐行读取文件。每行作为一项添加到数组中。问题是,当我逐行读取时,我必须根据文件中的行数创建数组 我可以使用两个独立的,而循环一个用于计数,然后创建数组,然后添加项目。但是,对于大文件来说,它并不高效 try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) { String line = ""; int maxRows = 0; while ((line = br.readLi

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

我可以使用两个独立的
,而
循环一个用于计数,然后创建数组,然后添加项目。但是,对于大文件来说,它并不高效

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
...

不能调整数组的大小。改用
ArrayList
类:

private ArrayList<OneRow> theRows;

...

theRows.add(new OneRow(maxColumns));
private ArrayList theRows;
...
添加(新的OneRow(maxColumns));

<代码> > p>我会考虑使用数据结构。如果您不熟悉ArrayList的工作方式,我会仔细阅读文档。

检查。ARARYLIST是一个可抗拒的数组,相当于C++向量。
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()); 
}
try(BufferedReader br=new BufferedReader(new FileReader(convertedFile)))
{ 
List str=new ArrayList();
字符串行=”;
而((line=br.readLine())!=null){
str.add(第行拆分(“”);
} 
} 
catch(filenotfound异常){
System.out.println(e.getMessage());
}捕获(IOE){
System.out.println(e.getMessage());
}

您可以使用一个ArrayList。另外:“readAllLines”:它向
行添加了什么?我想添加
str
我想添加
String[]
theRows
。你的意思是
private ArrayList theRows?如果没有初始赋值,将抛出NPE@mahmood它添加
OneRow
对象,就像在原始代码中一样。@mahmood这是因为它是
列表
而不是
列表
。无论如何,不要使用第二个。如果您想要2D数组,请使用
List
。为什么需要制作数组列表?因此,您的
str
实际上是我的
theRows
。对吗?我的str就像你的数组str在这两个项目之间有表格还是只有一个空格?