从文本文件实例化一个类

时间:2018-11-19 16:17:36

标签: java file-io instantiation

我有一个文本文件,其中包含姓名,电话号码和员工ID。

示例:

Chris Cotton
5555555555
CCOTTON

Joshua Trammell
5555555555
JTRAMMELL

我有一个名为Employee的类,它带有一个构造函数,该构造函数接受Name,Phone number和ID。

如何使用该文本文件以员工ID作为对象名称来实例化文本文件中每个记录的员工类?

package com.evolution.model;

public class Employee {
    private String name;
    private int phoneNumber;
    private String employeeId;

    public Employee(String name, int phoneNumber, String employeeId) {
        this.name = name;
        this.phoneNumber = phoneNumber;
        this.employeeId = employeeId;
    }

1 个答案:

答案 0 :(得分:0)

您可以逐行读取文件,并且可以在数组中保持三行连续,并且一旦捕获到三行,就可以按照我在main方法中显示的方式使用其Object构造器构造employee对象。

这是您可以使用的示例代码。为了安全起见,我已将phoneNumber的数据类型从int更改为String,因为电话号码可能仅包含数字,也可能不包含数字。但是,如果您确定您的电话号码仅包含也不以零开头的数字,则可以在for循环的构造函数创建调用中写Integer.parseInt(fileLines.get(i + 1))而不是仅写fileLines.get(i + 1)

这是相同的示例代码,

public class Employee {
    private String name;
    private String phoneNumber;
    private String employeeId;

    public Employee(String name, String phoneNumber, String employeeId) {
        this.name = name;
        this.phoneNumber = phoneNumber;
        this.employeeId = employeeId;
    }

    public String toString() {
        return String.format("name: %s, phoneNumber: %s, employeeId: %s",
                new Object[] { name, phoneNumber, employeeId });
    }

    public static void main(String args[]) throws Exception {
        try (BufferedReader reader = new BufferedReader(new FileReader("emp.txt"));) {
            String line = null;

            int counter = 0;
            String[] lineObject = new String[3];
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }
                lineObject[counter++] = line;
                if (counter == 3) {
                    counter = 0;
                    Employee employee = new Employee(lineObject[0], lineObject[1], lineObject[2]);
                    System.out.println(employee);
                    // employee.dowhatever();
                }
            }
        }
    }
}

执行后,该程序将打印以下输出

name: Chris Cotton, phoneNumber: 5555555555, employeeId: CCOTTON
name: Joshua Trammell, phoneNumber: 5555555555, employeeId: JTRAMMELL