我目前需要将CSV文件中的数据作为对象导入到数组中。然而,数据并非都是相同的类型,并且一行数据的格式如“Tom,Jones,95846,657.45”。我能够解析文件但似乎无法弄清楚如何将这些数据存储到数组中。我将需要根据姓名和号码等不同要求对这些数据进行排序。
import java.io.*;
import java.util.*;
public class People {
public static void main(String[] args) {
File file = new File("People.csv");
People peopleArr[] = new People[100];
try{
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter(",");
while(inputFile.hasNext()){
// Store the data into array
}
inputFile.close();
}catch (FileNotFoundException e){
System.out.println("Check file");
}
}
}
答案 0 :(得分:0)
也许像这样:
public static People[] readPeople(File file) {
List<People> people = new ArrayList<>(100);
try (Scanner inputFile = new Scanner(file)) {
inputFile.useDelimiter(",");
while (inputFile.hasNext()) {
People obj = new People();
// e.g. line is equals to John,Done
// obj.setFirstName(inputFile.next());
// obj.setLastName(inputFile.next());
people.add(obj);
}
} catch(FileNotFoundException e) {
System.out.println("Check file");
}
return people.toArray(new People[people.size()]);
}