Reading contents of a file into class objects

2020-07-29 23:54发布

I have a text file of employee entries as follows:

000, first name1, middle name1
001, first name2, middle name2
002, first name3, middle name3
003, first name4, middle name4
004, first name5, middle name5

And I have a class Employee as follows:

public class Employee {
    public int id;
    public String fName;
    public String mName;
    public String lName;
}

I've read the contents of the file into an array. But what I want is to construct an array of objects of class Employee, and a way for each attribute of the class to be initialised with each entry. Something like this:

Employee e[] = new Employee[5];

Checking the details of each object in the array...

e[0].id = 000
e[0].fName = "first name1"
e[0].mName = "middle name1"
e[0].lName = "last name1"

Then,

e[1].id = 001

And so on...

Is there any way I can do this?

标签: java
4条回答
等我变得足够好
2楼-- · 2020-07-30 00:43

Read the file and loop over its content line by line. Then parse the lines and create a new Employee() in each iteration. Set your values, such as id and name. Finally, add your new Employee instance to a List<Employee> and continue with the next entry.

// Read data from file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {

    // List to collect Employee objects
    List<Employee> employees = new ArrayList<Employee>();

    // Read file line by line
    String line = "";
    while ((line = br.readLine()) != null) {
       // Parse line to extract individual fields
       String[] data = this.parseLine(line);

       // Create new Employee object
       Employee employee = new Employee();
       employee.id = Integer.valueOf(data[0]);
       employee.fName = data[1];
       employee.mName = data[2];

       // Add object to list
       employees.add(employee);
    }

    // Further process your Employee objects...
}

Also, there are CSV libraries that can handle all the nasty parts of reading a file that has comma separated values. I'd suggest using OpenCSV, for example.

查看更多
\"骚年 ilove
3楼-- · 2020-07-30 00:47
public class Employee {
    public int id;
    public String fName;
    public String mName;
    public String lName;
    public Employee(String line) {
        String[] split = line.split(",");
        id = Integer.parseInt(split[0]);
        fName = split[1];
        mName = split[2];
        lName = split[3];
    }
}

Since you already read the file into array (of string I suppose).

String[] lines = ....;
Employee[] employees = new Employee[lines.length];
for(int i = 0; i < lines.length; i++) {
     employees[i] = new Employee(lines[i]);
}

There you go... you have an array of employees.

查看更多
等我变得足够好
4楼-- · 2020-07-30 00:52

try :

public static void main(String[] args) throws IOException {

    File f1 = new File("d:\\data.txt");
    Scanner scanner = new Scanner(f1);
    List<Employee1> empList=new ArrayList<>();
    while(scanner.hasNextLine()){
        String data[]=scanner.nextLine().split(",");
        empList.add(new Employee(Integer.parseInt(data[0]),data[1],data[2],data[3]));
    }
    scanner.close();
    System.out.println(empList);
}

Employee.java

 class Employee{
        public int id;
        public String fName;
        public String mName;
        public String lName;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getfName() {
            return fName;
        }
        public void setfName(String fName) {
            this.fName = fName;
        }
        public String getmName() {
            return mName;
        }
        public void setmName(String mName) {
            this.mName = mName;
        }
        public String getlName() {
            return lName;
        }
        public void setlName(String lName) {
            this.lName = lName;
        }
        public Employee(int id, String fName, String mName, String lName) {
            super();
            this.id = id;
            this.fName = fName;
            this.mName = mName;
            this.lName = lName;
        }
        @Override
        public String toString() {
            return "Employee [id=" + id + ", fName=" + fName + ", mName="
                    + mName + ", lName=" + lName + "]";
        }

}
查看更多
【Aperson】
5楼-- · 2020-07-30 00:56

Here already answers posted but I still gonna post mine...

package com.stackoverflow.java.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Employee {
public int id;
public String fName;
public String mName;

public Employee(int id, String fName, String mName) {
    this.id = id;
    this.fName = fName;
    this.mName = mName;
}


public static void main(String[] args) throws IOException {
    Employee[] e = new Employee[5];

    FileReader fr=new FileReader("YourDoc.txt");
    BufferedReader br=new BufferedReader(fr);
    String line="";
    String[] arrs=null;
    int num=0;
    while ((line=br.readLine())!=null) {
        arrs=line.split(",");

        e[num] = new Employee(Integer.valueOf(arrs[0]), arrs[1], arrs[2]);

        num++;
    }
    br.close();
    fr.close();

    for(int i=0 ; i< e.length; i++) {
        System.out.println(e[i].id + " and " + e[i].fName + " and " + e[i].mName);
    }
}

}

查看更多
登录 后发表回答