概述
import java.io.*; import java.time.LocalDate; import java.util.Scanner; public class Test { public static void main(String[] args){ // TextFileTest.test(); // RandomAccessTest.test(); } } /* 2.2.3 以文本格式储存对象 */ class Employee { private String name; private double salary; private LocalDate hireDay; public static final int NAME_SIZE = 30; public static final int RECORD_SIZE = 50; public Employee(String name, double salary, LocalDate hireDay) { this.name = name; this.salary = salary; this.hireDay = hireDay; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public LocalDate getHireDay() { return hireDay; } public void setHireDay(LocalDate hireDay) { this.hireDay = hireDay; } @Override public String toString() { return "Employee{" + "name='" + name + ''' + ", salary=" + salary + ", hireDay=" + hireDay + '}'; } } class TextFileTest { public static void test() { Employee[] staff = new Employee[]{ new Employee("A", 10, LocalDate.now()), new Employee("B", 20, LocalDate.now()), new Employee("C", 30, LocalDate.now()) }; try(PrintWriter out = new PrintWriter("employee.dat","UTF-8")) { writeData(staff,out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try (Scanner in = new Scanner(new FileInputStream("employee.dat"))) { Employee[] newStaff = readData(in); for (Employee e : newStaff) { System.out.println(e); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static void writeData(Employee[] employees, PrintWriter out) { out.println(employees.length); for (Employee e : employees) { writeEmployee(out,e); } } private static void writeEmployee(PrintWriter out, Employee employee) { out.println(employee.getName()+"|"+employee.getSalary()+"|"+ employee.getHireDay()); } private static Employee[] readData(Scanner in) { int n = in.nextInt(); in.nextLine(); Employee[] employees = new Employee[n]; for (int i = 0; i < n; i++) { employees[i] = readEmployee(in); } return employees; } private static Employee readEmployee(Scanner in) { String line = in.nextLine(); String[] tokens = line.split("\|"); String name = tokens[0]; double salary = Double.parseDouble(tokens[1]); //*****************有趣的写法**************** LocalDate hire = LocalDate.parse(tokens[2]); //****************************************** return new Employee(name, salary, hire); } }
《Java核心技术卷二》笔记
转载于:https://www.cnblogs.com/junjie2019/p/10596861.html
最后
以上就是愉快秋天为你收集整理的Java文本类型输入与输出的全部内容,希望文章能够帮你解决Java文本类型输入与输出所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复