package textFile;
import java.io.*;
import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import abstractClass.Employee;
public class TestFileTest {
public static void main(String[] args) throws IOException, ParseException {
Employee[] staff = new Employee[3];
staff[0] = new Employee("First", 1111, 1987, 12, 15);
staff[1] = new Employee("Second", 2222, 1989, 10, 1);
staff[2] = new Employee("Third", 3333, 1990, 3, 15);
try (PrintWriter out = new PrintWriter("employee.txt", "UTF-8")) {
writeData(staff, out);
}
try (Scanner in = new Scanner(new FileInputStream("employee.txt"), "UTF-8")) {
Employee[] newStaff = readData(in);
for (Employee e : newStaff)
System.out.println(e);
}
}
private static void writeData(Employee[] employees, PrintWriter out) throws IOException {
out.println(employees.length);
for (Employee e : employees)
writeEmployee(out, e);
}
private static Employee[] readData(Scanner in) throws ParseException {
int n = in.nextInt();
in.nextLine();
Employee[] employees = new Employee[n];
for (int i = 0; i < n; i++) {
employees[i] = readEmployee(in);
}
return employees;
}
public static void writeEmployee(PrintWriter out, Employee e) {
out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
}
public static Employee readEmployee(Scanner in) throws ParseException {
String line = in.nextLine();
String[] tokens = line.split("\\|");
//System.out.println(tokens[2]);
String name = tokens[0];
double salary = Double.parseDouble(tokens[1]);
DateTimeFormatter df = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US);
LocalDate hireDate = LocalDate.parse(tokens[2], df);
int year = hireDate.getYear();
int month = hireDate.getMonthValue();
int day = hireDate.getDayOfMonth();
return new Employee(name, salary, year, month, day);
}
}
以文本格式存储对象程序实例
猜你喜欢
转载自blog.csdn.net/weixin_43207025/article/details/104383069
今日推荐
周排行