【问题标题】:Java, Reading objects from a file and adding them to an arraylistJava,从文件中读取对象并将它们添加到数组列表中
【发布时间】:2018-05-16 13:59:37
【问题描述】:

我有一个带有两个实例变量的 Client 类:firstName 和 surname

现在,我有另一个类,我想从文本文件中读取名称并将它们存储在 Client 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();
        }

    }

}

现在这是我运行 main 方法时得到的结果:

约翰·史密斯约翰·史密斯

迈克高盛迈克高盛

艾玛·斯通艾玛·斯通

我做错了什么?我的文本文件只是上述名称的列表,我希望将名字和姓氏存储为单独的信息,这样当我打印时,它会为我的文本文档中的每个人打印名字 + 姓氏

有什么建议吗?

【问题讨论】:

  • 好吧,您使用tokenize[0] 作为名字和姓氏的事实并没有帮助。您是否已调试代码以找出问题所在?逐行浏览您的代码,并仔细注意每一行的结果 - 哪里不符合您的期望?
  • (提示:你只有一行,但你试图用换行符来分割它。你如何期望它实际分割任何东西?)
  • 谢谢大家!看我下面的代码,它似乎解决了问题

标签: java list arraylist bufferedreader filereader


【解决方案1】:
String[] tokenize1 = fileRead.split("\\s+");
String tempFirstName = tokenize1[0];
String tempSurname = tokenize1[1];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-26
    • 2017-07-14
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2018-12-29
    • 2021-04-04
    • 2020-10-03
    相关资源
    最近更新 更多