2014-12-05 41 views
0

我有一個文本文件「addresses.txt」,用於保存關於某人的信息。我創建了一個Person類,我需要從這個文本文件讀取和存儲信息到一個ArrayList。 我的錯誤是當試圖讀取文本文件,我不能將它添加到我的ArrayList因爲字符串爭議。真的失去了這一點,我知道這可能是一個簡單的解決方案,但我只是無法弄清楚。閱讀並將文本文件添加到Java對象的ArrayList中

如果需要,下面是我的一些Person類:

public class Person { 
private String firstName; 
private String lastName; 
private String phoneNumber; 
private String address; 
private String city; 
private String zipCode; 

private static int contactCounter = 0; 

public Person(String firstName, String lastName){ 
    this.firstName = firstName; 
    this.lastName = lastName; 
    contactCounter++; 
} 

public Person(String firstName, String lastName, String phoneNumber){ 
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.phoneNumber = phoneNumber; 
    contactCounter++; 
} 

public Person(String firstName, String lastName, String address, String city, String zipCode){ 
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.address = address; 
    this.city = city; 
    this.zipCode = zipCode; 
    contactCounter++; 
} 

這裏是我的主類:

import java.io.*; 
import java.util.Scanner; 
import java.util.ArrayList; 
public class Rolodex { 

public static void main(String[] args) { 
    ArrayList <Person> contactList = new ArrayList <Person>(); 
    readFile(contactList); 
} 

public static void readFile(ArrayList <Person> contactList){ 
    try{ 
     Scanner read = new Scanner(new File("addresses.txt")); 
     do{ 
      String line = read.nextLine(); 
      contactList.add(line); //MY ERROR IS HERE. I know why its happening just not how to fix. 
     }while(read.hasNext()); 
     read.close(); 
    }catch(FileNotFoundException fnf){ 
     System.out.println("File was not found."); 
    } 
} 
+0

[解析行](http://stackoverflow.com/questions/16021218/parse-full-name),使對象然後添加到列表中。 – 2014-12-05 08:46:29

+0

您需要解析文件中的行以獲取相關信息,然後使用此數據創建一個新的Person對象,並將該對象添加到列表中。 – 2014-12-05 08:46:40

回答

1

您嘗試添加字符串行成的人陣。 您不能將字符串轉換爲Person。 修復:嘗試實現某種線解析器 例如。你的行看起來像這個"adam;bra;555888666;"你必須使用line.split(";") 解析這個字符串,它現在創建你的字符串(String [])數組,現在只需使用你的構造函數來創建Person並將他添加到contactList 例如。

contactList.add(New Person(parsedString[0], parsedString[1], parsedString[2])); 
0

而不是使用文本文件,您應該使用JSON文件。和GSON庫一樣,在文件中獲取和寫入數據更容易...

+0

還有更多,你可以使用JSON文件直接保存你的對象! – 2017-12-28 22:08:52