将文本文件读入集合问题

时间:2013-05-18 09:51:54

标签: java file-io

我有一个文本文件,里面有以下结构:

Daily Rainfall Totals (mm), Weather Station,(Meteorological Office Climatological Station TY12SDF) 
John Smith, DRE, RED Division, data obtained DEC 2011 
Format=Year, Month, 1-31 daily precipitation values. Any entry set to -99.99 means that no data exists for that day. 
2010      1   1.10   5.50   0.00   7.80   1.80   0.00   0.00   0.00   0.00   0.70   0.70   0.01   0.60   2.40  14.30   1.00   0.30   1.20   0.00   0.00   9.90   0.30   1.10   0.40   0.01   0.20   0.10   2.00   0.00   0.00   0.00
2010      2  10.40   0.00   3.00   0.90   0.00   0.30   0.01   0.00   0.00   0.00   0.00   0.10   0.00   1.00  10.00   3.30   0.10   2.90   0.00   0.01   0.01   0.00   5.20   0.01   9.90   9.00   0.00   0.01 -99.99 -99.99 -99.99
2010      3   0.01   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.10   0.00   2.20   9.00   4.70   2.00   2.50   4.10   0.90  11.10   3.90   0.01   0.30   5.60  17.40   0.30

我想将值读入集合但我不知道应该使用哪一个?这是因为我打算将每年的数据绑定到GUI控件中。

我知道如何读取逗号分隔的数据1,2,3,如下所示:

File file = new File("sample.txt");
ArrayList<String> num = new ArrayList<String>();
Scanner in = new Scanner(file);
while (in.hasNextLine()){
  num.add(in.nextLine());
}

EDIT 但问题是我想在我读完文件后在集合中创建一个结构: [2010] [1] [2.2,2.3,2.4,2.5] 2010年是年份,1是月份,其余是数据。

我将如何实现这一目标?多维数组?

1 个答案:

答案 0 :(得分:1)

我应该如何将数据读入集合中,以便将其绑定到Java中的GUI组件?

这里有一个非常优雅的选择,就是使用ListModel(文档here)。 ListModel可以用作JList的后端数据存储。

示例

您可以使用DefaultListModel实施。

ListModel listData = new DefaultListModel();
listData.add() // Populate your list model.

JList list = new JList(listData);
// Create the JList with the list data.