我有一个文本文件“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