0

我想将 Text.txt 文件中的数据添加到 java 中的 ArrayList。

我创建了一个只有 getter 和 setter 的 POJO Employee 类:

public class Employee {
    private String name;
    private String designation;
    private String joiningDate;

    public Employee(String name, String designation, String joiningDate) {
        this.name = name;
        this.designation = designation;
        this.joiningDate = joiningDate;
    }

    public String getJoiningDate() {
        return joiningDate;
    }

    public void setJoiningDate(String joiningDate) {
        this.joiningDate = joiningDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }
}

这是我的主要课程:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;

public class MainClass {
    public static void main(String[] args) throws FileNotFoundException {

        ArrayList<Employee> emplo = new ArrayList<Employee>();
        BufferedReader file = new BufferedReader(new FileReader("D://Test.txt"));

        try {
            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = file.readLine()) != null) {
                String token[] = line.split("|");
                String name = token[0];
                String designation = token[1];
                String joiningDate = token[2];
                Employee emp = new Employee(name, designation, joiningDate);
                emplo.add(emp);

            }
            for (int i = 0; i < emplo.size(); i++) {
                System.out.println(emplo.get(i).getName() + " "
                        + emplo.get(i).getDesignation() + " "
                        + emplo.get(i).getJoiningDate());
            }

            file.close();
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}

文本文件数据:

John|Smith|23

Rick|Samual|25

Ferry|Scoth|30

我想要的是:

John Smith 23

Rick Samual 25

Ferry Scoth 30

在这方面的任何帮助都将是可观的

4

2 回答 2

4

Split 方法将正则表达式作为参数,而不是纯字符串。这将完成这项工作:

String token[] = line.split("\\|");
于 2014-04-15T07:37:03.787 回答
2

实际上 split() 方法将正则表达式作为其参数。常规的“|” 用作特殊字符以将其用作普通字符使用

line.split("\\|");

这应该这样做

一切顺利

于 2014-04-15T07:40:08.837 回答