Java 将文件内容读入类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32265533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:14:34  来源:igfitidea点击:

Reading contents of a file into class objects

java

提问by Pastasaurus Rex

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:

我有一个 Employee 类,如下所示:

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 的对象数组,以及一种用每个条目初始化类的每个属性的方法。像这样的东西:

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?

有什么办法可以做到这一点吗?

采纳答案by Ferdinand Neman

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.

你去吧……你有一群员工。

回答by user1438038

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 Employeeinstance to a List<Employee>and continue with the next entry.

读取文件并逐行循环其内容。然后解析这些行并new Employee()在每次迭代中创建一个。设置您的值,例如 id 和 name。最后,将您的新Employee实例添加到 aList<Employee>并继续下一个条目。

// 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.

此外,还有一些 CSV 库可以处理读取具有逗号分隔值的文件的所有令人讨厌的部分。例如,我建议使用OpenCSV

回答by J.Lyu

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

}

}

回答by Rustam

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

雇员.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 + "]";
        }

}