简体   繁体   中英

Java, Reading objects from a file and adding them to an arraylist

I have a Client class with two instance variables: firstName and surname

Now, I have another class in which I want to read names from a text file and store them in the Client ArrayList

Here's the code:

import java.io.*;
import java.util.*;

public class Arraylists
{
  public static void main(String [] args) throws FileNotFoundException
    {

     List<Client> clients = new ArrayList<Client>();


     try
     {

     BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\...\\Desktop\\InputTest.txt")); 


     String fileRead = br.readLine();   


            while (fileRead != null)
            {

                String[] tokenize = fileRead.split("\\n");

                String tempFirstName = tokenize[0];
                String tempSurname = tokenize[0];

                Client tempObj = new Client(tempFirstName, tempSurname);

                clients.add(tempObj);

                fileRead = br.readLine();
            }


            br.close();
        }


        catch (FileNotFoundException fnfe)
        {
            System.out.println("file not found");
        }

        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }


        for (Client client : clients)
        {
            System.out.println(client);
            System.out.println();
        }

    }

}

Now this is what I'm getting when I run the main method:

John Smith John Smith

Mike Goldman Mike Goldman

Emma Stone Emma Stone

What am I doing wrong? My text file is just a list of the above names and I want the first name and the surname to be stored as a separate pieces of information so that when I print, it prints firstName + surname for every single person in my text document

Any suggestions?

String[] tokenize1 = fileRead.split("\\s+");
String tempFirstName = tokenize1[0];
String tempSurname = tokenize1[1];

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