简体   繁体   中英

Read and Add Text File to an ArrayList of Object in Java

I have a text file "addresses.txt" that holds information about a person. I have created a Person class and I need to read and store the information from this text file into an ArrayList. My error is when trying to read the text file I can not add it to my ArrayList because of the String arguement. Really lost at this point I know it may be a simple solution but I just cant figure it out.

Here is some of my Person class if needed:

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++;
}

Here is my main class:

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.");
    }
}

You try to add String line into Person array. You can't cast String to Person. Fix:Try to implement some kind of line parser eg. Your line looks like this "adam;bra;555888666;" you have to parse this string using line.split(";") it creates you array of Strings (String[]) now just use your constructors to create Person and add him into contactList eg.

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

Instead of using a text file, you should use a JSON file. And with the GSON library, it's more easy to get and write data in files...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM