java从csv数据创建对象并保存到列表

时间:2017-06-15 21:22:53

标签: java

我需要从csv文件读取数据,它的顶点值和图形数据的距离采用与此类似的格式:

Bejing,Tokio,530  
NewYork,LasVegas,800

当我从文件中读取它时,我需要将输入数据转换为具有两个城市作为Vertex对象的Edge对象,如下所示:Edge edge = new Edge(new Vertex(line[0]), new Vertex(line[1]), Integer.parseInt(line[2]));我想将每个新的Vertex对象添加到没有重复顶点的顶点列表。 我不想将数据硬编码到源代码中。

1 个答案:

答案 0 :(得分:0)

我认为您想要“动态”读取数据,因为您不知道如何获取不同的索引,对吧?如果是这样,请查看OpenCSV

只需导入库,对于您的示例,它将是这样的:

final CSVReader reader = new CSVReader(new FileReader("graph_data.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
  final Edge edge = new Edge(new Vertex(nextLine[0]), new Vertex(nextLine[1]),
      Integer.parseInt(nextLine[2])));
  // ...make sure you store this newly created edge somewhere else
  // since the reference is lost once the while loop repeats
}
// ...close/release any I/O resources and continue!