gpt4 book ai didi

java - 将文本文件数据添加到数组java

转载 作者:行者123 更新时间:2023-12-01 08:03:55 24 4
gpt4 key购买 nike

我想将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

任何帮助都将是值得赞赏的

最佳答案

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

String token[] = line.split("\\|");

关于java - 将文本文件数据添加到数组java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23077204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com