阅读并将文本文件添加到Java对象的ArrayList中
问题描述:
我有一个文本文件“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.");
}
}
答
您尝试添加字符串行成的人阵。 您不能将字符串转换为Person。 修复:尝试实现某种线解析器 例如。你的行看起来像这个"adam;bra;555888666;"
你必须使用line.split(";")
解析这个字符串,它现在创建你的字符串(String [])数组,现在只需使用你的构造函数来创建Person并将他添加到contactList 例如。
contactList.add(New Person(parsedString[0], parsedString[1], parsedString[2]));
答
而不是使用文本文件,您应该使用JSON文件。和GSON库一样,在文件中获取和写入数据更容易...
+0
还有更多,你可以使用JSON文件直接保存你的对象! – 2017-12-28 22:08:52
[解析行](http://stackoverflow.com/questions/16021218/parse-full-name),使对象然后添加到列表中。 – 2014-12-05 08:46:29
您需要解析文件中的行以获取相关信息,然后使用此数据创建一个新的Person对象,并将该对象添加到列表中。 – 2014-12-05 08:46:40