3 回答
TA贡献1725条经验 获得超7个赞
两点:-
1 - 如下更改您的主列表。您不应该创建通用列表(原始类型)。如果您将列表创建为原始类型,您将能够输入任何数据类型。由于可能存在多种数据类型列表,因此会产生问题。
2 - 当您进入 while 循环时,创建/分配新引用到子列表,然后将其添加到主列表。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
List<String> sub = new ArrayList<String>();
List<List<String>> master = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
sub = new ArrayList<String>();
sub.add(line);
master.add(new ArrayList<String>(sub));
// System.out.println(sub);
sub.remove(0);
// System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);
}
}
TA贡献1883条经验 获得超3个赞
尝试将变量声明移到subwhile 块上。
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
List<List> master = new ArrayList<List>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
List<String> sub = new ArrayList<String>();
sub.add(line);
master.add(sub);
// System.out.println(sub);
// sub.remove(0);
// System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);
TA贡献1794条经验 获得超8个赞
你可以这样做
public static List<String[]> getTestData(String fileName) {
List<String[]> records = new ArrayList<String[]>();
try {
String record;
BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
while ((record = file.readLine()) != null) {
System.out.println(record);
String fields[] = record.split(",");
records.add(fields);
}
file.close();
return records;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
添加回答
举报