我正在处理一项任务,要求我使用流API从.csv文件中读取,遍历每一行并使用这些行构建一个对象。对象类称为Planet,它是:
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
@Override
public String toString() {
return name;
}
}
因此,使用流API来遍历.cvs文件的每一行,我需要创建类Planet的对象。
我没有取得任何进展,因为我真的不确定如何使用流API
public class Space {
public List<Planet> csvDataToPlanets(String filePath) {
return null;
}
答案 0 :(得分:0)
尝试下面的代码段。
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());
br.close();
有关详细信息,请查看此link
答案 1 :(得分:0)
public static void main(String args[]) {
String fileName = "<Your File Path"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(<Method to split the string based with ',' as delimiter and call Constructor using Reflection API>);
} catch (IOException e) {
e.printStackTrace();
}
}