2012-04-11 72 views
0

在person.txt中,我们存储了该人员的详细信息。 看起来像这样。文件读取器直到结尾才读取所有数据

John 
Smith 
aösldkjf 
5 
8645 
asdfasf 
0441234545 
++++++ 
Adam 
Gilchrist 
ads 
asf 
asf 
asfd 
0441234546 
++++++ 

然后我们建立了FileManager类来读取这个文件中的数据。 它标识有两个不同的条目。 但它始终读取前8行,不会继续。由于第一个人(例如: - John Smith)被添加了两次到名为AddressBook的“LinkedList”。

//文件管理器类

public class FileManager { 

    public static void readFile() { 

     Scanner x; 

     LinkedList<String> tempList = new LinkedList<String>(); 

     try { 
      x = new Scanner(new File("Person.txt")); 

      @SuppressWarnings("unused") 
      String temp = null; 

      while (x.hasNext()) { 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 
       tempList.add(x.next()); 

       Person person = new Person(); 

       person.addFilePerson(tempList); 

       Main.addressBook.add(person); 

      } 
     } catch (Exception e) { 
      System.out.println("could't find the file"); 
     } 
    } 
} 

// addFilePerson方法的类人

public void addFilePerson(LinkedList<String> list){ 

    vorname = list.get(0); 
    nachname = list.get(1); 
    strasse = list.get(2); 
    hausnummer = list.get(3); 
    plz = list.get(4); 
    telefon = list.get(5); 
    wohnort = list.get(6); 
} 

回答

1

你正在创建一个LinkedList<String>,并多次添加到它。移动此行:

LinkedList<String> tempList = new LinkedList<String>(); 

while循环。或者 - 优选地,IMO - 使用不同属性的不同部分:

// TODO: Consider what happens if the file runs out half way through a person... 
while (x.hasNext()) { 
    Person person = new Person(); 
    person.setFirstName(x.next()); 
    person.setLastName(x.next()); 
    person.setStreet(x.next()); 
    person.setTown(x.next()); 
    person.setTelephoneNumber(x.next()); 
    person.setCity(x.next()); // Or whatever... 

    Main.addressBook.add(person); 
} 

有周围Person创建一个“建设者”型,使Person本身不变的其他选项,你可能要创建一个单独的Address键入...

1

您应该清除(或重新创建)您的列表,从文件中读取人员。否则,您将继续将同一个人(您阅读的第一个人)添加到地址簿中。因此,要么每次循环中重新创建您的临时列表,乔恩建议,或之后每轮清除:

 while (x.hasNext()) { 
      tempList.add(x.next()); 
      ... 

      Main.addressBook.add(person); 

      tempList.clear(); 
     } 
+0

的代码只是一行。完美的作品。 – 2012-04-15 17:23:36

1

它实际上在移动。这条线:

person.addFilePerson(tempList); 

您发送tempList作为参数,但在addFilePerson方法,你总是读tempList的第7项。您应该在循环的每次迭代中清除tempList

0

您应该使用nextLine()和hasNextLine()来代替next()和hasNext()。扫描仪具有上下文感知功能,因此默认令牌读取行为可能不是基于行的。

0

你会更好做

Person person = new Person(); 
Address address = new Address(); 
person.setAddress(address); 

person.setFirstName(x.next()); 
person.setLastName(x.next()); 
address.setStreetName(x.next()); 
address.setHouseNumber(x.next()); 
address.setZipCode(x.next()); 
person.setPhoneNumber(x.next()); 
address.setCityName(x.next());