【发布时间】:2020-12-30 13:44:48
【问题描述】:
我正在尝试将 csv 数据读取到 java,并将每个字段设置为对象并添加到数组列表中,但我得到了一个不同的 csv 文件,它缺少一个值,错误是 java.lang.ArrayIndexOutOfBoundsException: 6。
public void loadAircraftData(Path p) throws DataLoadingException {
try {
//open the file
BufferedReader reader = Files.newBufferedReader(p);
//read the file line by line
String line = "";
//skip the first line of the file - headers
reader.readLine();
while( (line = reader.readLine()) != null) {
//each line has fields separated by commas, split into an array of fields
String[] fields = line.split(",");
//put some of the fields into variables: check which fields are where atop the CSV file itself
String tailcode = fields[0];
String model = fields[1];
String type = fields[2];
//Manufacturer manufacturer = fields[3];
String staringPoistion = fields[4];
int seats = Integer.parseInt(fields[5]);
int cabincrewrequired= Integer.parseInt(fields[6]);
//create an Aircraft object, and set (some of) its properties
Aircraft a = new Aircraft();
a.setTailCode(tailcode);
a.setModel(model);
a.setTypeCode(type);
//a.setManufacturer(Manufacturer);
a.setStartingPosition(staringPoistion);;
a.setSeats(seats);
a.setCabinCrewRequired(cabincrewrequired);
a.setManufacturer(Manufacturer.AIRBUS);
a.setManufacturer(Manufacturer.FOKKER);
a.setManufacturer(Manufacturer.EMBRAER);
//add the aircraft to our list
aircraft.add(a);
【问题讨论】:
-
可以上传csv格式的文件内容吗?
-
第二行在cabinetcrewrequired 列中没有值。因此,您的 fields 数组在第二次迭代中只有 6 个元素。您的代码需要注意缺少的字段。如果您逐步调试代码,您会清楚地看到发生了什么。
-
我知道错误,我只是不知道如何让我的代码知道 csv 文件中缺少的字段
-
您可以遍历字段数组的长度,然后根据索引设置字段
-
我应该怎么做呢?使用循环?