阅读文件的指南

时间:2013-05-30 20:17:38

标签: java file

我有一个关于文件阅读和写作的问题,因为我最近了解了它们。

如果我的文件包含如下数据:

1 apartment 600000 2 house 500000 3 house 1000 4 something 5456564

(id name price / int string double)

这一切都在一行,

我可以执行instanceof之类的操作,以便计算出1种类型的价格 像房子的所有价格一样?

1 个答案:

答案 0 :(得分:2)

我不清楚你当前是如何存储你读的数据,但你应该做的是将数据读入一些数据对象的列表:

public class Dwelling
{
    int Id;
    String name;
    int price;
}

然后将它们存储在某些数据结构中。我认为ArrayLists的HashMap可能对您的目的很方便:

HashMap<String, ArrayList<Dwelling>> types = new HashMap<String, ArrayList<Dwelling>>();

// Loop through records in file
while(moreRecords)
{
    // Read the next record into a data object
    DwellingType d = getNextDwelling();

    // Store the record in the data structure
    ArrayList<Dwelling> list = types.get(d.getName());
    if (list == null)
    {
        list = new ArrayList<Dwelling>();
        types.put(d.getName(), list);
    }
    list.add(d);
}

要访问特定类型的记录列表,您只需拨打HashMap.get()

ArrayList<Dwelling> list = types.get("Apartment");

然后你可以遍历记录来做你需要做的事情:

int totalPrice = 0;
for (Dwelling d : list)
{
    totalPrice += d.price;
}