我有一个包含四列和多行的CSV文件:
a,b,c,d / n
a,b,c,d / n
我成功读取了.CSV文件的内容并将其放入ArrayList中。如何将每一列分成一个数组?我想拥有arrayA,ArrayB,ArrayC,ArrayD。
Scanner scan = new Scanner(new File(copyUri));
ArrayList<String[]> records = new ArrayList<String[]>();
String[] record = new String[2];
while(scan.hasNext())
{
record = scan.nextLine().split(",");
records.add(record);
}
将它们分成同一循环内的数组。如果您不知道csv文件中的行数,我建议使用ArrayList。
Scanner scan = new Scanner(new File(copyUri));
ArrayList<String[]> records = new ArrayList<String[]>();
String[] record = new String[2];
ArrayList<String[]> a = new ArrayList<String[]>();
ArrayList<String[]> b = new ArrayList<String[]>();
ArrayList<String[]> c = new ArrayList<String[]>();
ArrayList<String[]> d = new ArrayList<String[]>();
while(scan.hasNext())
{
record = scan.nextLine().split(",");
a.add(record[0]);
b.add(record[1]);
c.add(record[2]);
d.add(record[3]);
records.add(record);
}
另一个效率较低的解决方案是找到记录列表的大小,使用该大小创建数组,然后用数据填充它们。
Scanner scan = new Scanner(new File(copyUri));
ArrayList<String[]> records = new ArrayList<String[]>();
String[] record = new String[2];
while(scan.hasNext()) {
record = scan.nextLine().split(",");
records.add(record);
}
int rows = records.size();
String[] a = new String[rows];
String[] b = new String[rows];
String[] c = new String[rows];
String[] d = new String[rows];
int j = 0;
for (String[] temp : records) {
a[j] = temp[0];
b[j] = temp[1];
c[j] = temp[2];
d[j] = temp[3];
j++;
}
我得到的第三个想法是使用一定的大小初始化数组(例如:5),并随需调整数组的大小,但是我认为这样做效率最低,因为每次调整大小时都必须将元素移到新数组中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句