Java 逐行读取文件并向数组中添加行
我想用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
,而循环一个用于计数,然后创建数组,然后添加项目。但是,对于大文件来说,它并不高效
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在这两个项目之间有表格还是只有一个空格?