我想在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());
}
Run Code Online (Sandbox Code Playgroud)
考虑private OneRow [] theRows;并OneRow定义为String [].该文件看起来像
Item1 Item2 Item3 ...
2,3 4n 2.2n
3,21 AF AF
...
Run Code Online (Sandbox Code Playgroud)
您无法调整阵列的大小.ArrayList改为使用该类:
private ArrayList<OneRow> theRows;
...
theRows.add(new OneRow(maxColumns));
Run Code Online (Sandbox Code Playgroud)