Reputation: 63
I want to add data from Text.txt file to ArrayList in java.
I had created a POJO Employee class with just getters and setters:
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;
}
}
And this is my main class :
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
}
}
}
Text file data:
John|Smith|23
Rick|Samual|25
Ferry|Scoth|30
What I want:
John Smith 23
Rick Samual 25
Ferry Scoth 30
Any help in this will be appreciable
Upvotes: 0
Views: 2248
Reputation: 8917
Split method takes regular expression as a parameter, not a plain string. This will do the job:
String token[] = line.split("\\|");
Upvotes: 4
Reputation: 3831
Actually split() method takes regular expression as its parameter. The regular '|' is used as special character to use it as plain character use
line.split("\\|");
This should do it
All the best
Upvotes: 2