首页 > 解决方案 > 使用字符串解析器并将输入文件传递给arraylist

问题描述

嗨,我正在尝试读取文件并将其存储在数组列表中,但我被困在这里。我还需要使用我不知道放在哪里的 String.split()。有什么我错过的吗?

我的代码是:

import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;

public class Employee
{
    private ArrayList<Employee> employees;
    private String name;
    public Employee()
    {
        employees = new ArrayList<Employee>();
        name = "";
    }

    public void readFile()
    {
        String filename = ("employees.txt");

        try
        {   FileReader inputFile = new FileReader(filename);

            try
            {
                while (parser.NextLine())
                {
                    Scanner parser = new Scanner(inputFile);
                    String employeeType = parser.nextLine();
                    System.out.println(employeeType);
                    String employeeNumber = parser.nextLine();
                    System.out.println(employeeNumber);
                    String employeeName = parser.nextLine();
                    System.out.println(employeeName);
                }
            }
            finally
            {
                System.out.println("Closing file");
                inputFile.close();
            }
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + "not found");
        }
        catch(IOException exception)
        {
            System.out.println("Unexpected I/O error occured");
        }
    }
}

标签: javaparsingarraylist

解决方案


假设您有并输入文件如下:

jinny 程序员 50000
john manager 75000

您已经正确设置了一些东西,但是您必须考虑的是如何实例化 Employee(它似乎只有一个无参数构造函数)。假设Employee有一个名字、一个头衔和一个薪水。这些是您的Employee. 当您在文件中阅读时,您希望在Employee阅读每一行时将这些属性设置为单一类型,其属性由示例文件中的空白字符分隔。

public class Employee {
    private String name;
    private String title;
    private Integer salary;

    //constructor + getters + setters
}

此外,对于遇到的每个员工,您都需要在员工之外构建一个包含您的员工信息的集合。

考虑以下可能存在于Employee类之外的示例。这就是您从数据文件中收集员工并填充员工属性的方式。

public static void main(String... args) {
    List<Employees> employees = readFile();

    //continue work on employees here
}

public static List<Employee> readFile()
{
    String filename = ("employees.txt");

    try
    {   FileReader inputFile = new FileReader(filename);

        Scanner scanner = new Scanner(inputFile);

        try
        {
            while (scanner.hasNextLine())
            {
                Employee e = new Employee();

                String line = scanner.nextLine();

                String [] lineSplit = line.split(" ");

                //populate employees here OR use a constructor on employee that accepts all 3 parameters
            }
        }

     //continue implementation here

推荐阅读