2017-06-15 76 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!