我有一個文本文件「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.");
}
}
[解析行](http://stackoverflow.com/questions/16021218/parse-full-name),使對象然後添加到列表中。 – 2014-12-05 08:46:29
您需要解析文件中的行以獲取相關信息,然後使用此數據創建一個新的Person對象,並將該對象添加到列表中。 – 2014-12-05 08:46:40