2017-06-15 100 views
0

我需要阅读从CSV文件中的数据,它的顶点值和距离的图形数据的格式与此类似:的Java创建CSV数据对象并保存到列表

Bejing,Tokio,530 
NewYork,LasVegas,800 

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

+2

你有什么问题? –

回答

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!