2015-03-31 62 views
0

我被困在如何去阅读/处理文件。文件的读取和处理

示例文件:

2 

    cow 
    moo 
    black 
    and white very fast 

    pig 
    pink 
    very slow 

的2指示在该文件中的条目的数量。空行。然后是对象的名称和两行特征。

基本上我很困惑,因为最好的方法是逐行读取输入并处理它,以便我可以创建指定的对象。

我在想我可以创建一个数组列表,然后从那里开始,但我不知道空白行分隔符将如何被采用。由于每个文件的元素数量可能不同,因此我不确定如何考虑这些因素。

+0

只需使用Scanner/BufferedReader,因为您知道文件的结构。 – kolossus 2015-03-31 20:28:36

回答

0

这听起来像你的问题是在概念层面比语法层次更多,所以我会尝试在该层次上回答。

首先,我并不认为开始的号码是必需的,但您可以使用它来检查您是否在事后跟踪。

我认为你应该创建一个描述你的对象的类,我们称它为“动物”类作为参考。构造函数应该获得一个数组列表,其中只包含与某个特定动物(您正在实例化的那个动物)相关的行的子集。该类的属性应该是你需要的任何东西(例如名字等)。

所以在伪码:

准备数组列表:

-read each line of file into arraylist 

消耗数组列表:

-read and save off the number of entries for checking later 
-read and ignore the first blank line 
-read line by line into another arraylist until the next blank line, pass your new array list to the constructor for your Animal class and then repeat this until you hit the end of file (making sure to construct the final object as well). 

“动物” 构造:

-Set the first entry in the arrayList passed to constructor as the animals Name. 
-Set remaining properties as required.... 

作为你可以创造动物将它们存储在一些数组中,最后您可以验证您是否使用在开始时存储的值创建了正确的数字。

相关问题