【发布时间】: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
...
【问题讨论】:
-
你可以使用 ArrayList。
-
还有:“readAllLines”:docs.oracle.com/javase/8/docs/api/java/nio/file/…