2017-12-02 89 views
1

我有一个客户端类有两个实例变量:名字和姓氏Java中,从文件读取的对象,并将它们添加到ArrayList

现在,我有我想从一个文本文件中读取名其他类并将其存储在客户端的ArrayList

下面的代码:

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(); 
     } 

    } 

} 

现在,这是当我运行的主要方法是什么我越来越:

约翰SMI TH约翰·史密斯

迈克高盛迈克高盛

艾玛斯通艾玛斯通

我在做什么错?我的文本文件只是上面名称的一个列表,我希望名字和姓氏作为单独的信息存储,以便在打印时,它会在我的文本文档中为每个人打印firstName +姓氏

有什么建议吗?

+0

那么事实上,你使用'tokenize [0]'的名字和姓氏都没有帮助。你有没有调试到你的代码来找出问题所在?逐行浏览你的代码,仔细注意每行的结果是什么 - 它不符合你的期望? –

+0

(提示:你有一条线,但你试图用换行符来分割它,你如何期待它真正地分割任何东西?) –

+0

谢谢你们!看到我的下面的代码,它看起来像它解决了这个问题 –

回答

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