io的使用
package com.tan.io; import java.io.*;
import java.util.*; class Employee{
private String name;
private double salary;
private Date hireDay; public Employee(String name,double salary,int year,int month,int day){
this.name=name;
this.salary=salary;
GregorianCalendar calendar=new GregorianCalendar(year,month-1,day);
hireDay=calendar.getTime();
} public String getName(){
return name;
} public double getSalary(){
return salary;
} public Date getHireDay(){
return hireDay;
} public void raiseSalary(double byPersent){
double raise=salary*byPersent/100;
salary+=raise;
}
} public class TextFileTest {
public static void main(String[] args)throws IOException{
Employee[] staff=new Employee[3];
staff[0]=new Employee("Carl Cracker", 75000, 1987,12,15);
staff[1]=new Employee("Harry Hacker",50000,1989,10,1);
staff[2]=new Employee("Tony Tester",40000,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 Employee[] readData(Scanner in) {
int n=in.nextInt();
in.nextLine(); Employee[] employees=new Employee[n];
for(int i=0;i<3;i++){
employees[i]=readEmployee(in);
}
return employees;
} private static Employee readEmployee(Scanner in) {
// TODO Auto-generated method stub
String line=in.nextLine();
String[] token=line.split("\\|");
String name=token[0];
double salary=Double.parseDouble(token[1]);
int year=Integer.parseInt(token[2]);
int month=Integer.parseInt(token[3]);
int day=Integer.parseInt(token[4]);
return new Employee(name, salary, year, month, day);
} private static void writeData(Employee[] staff, PrintWriter out) {
// TODO Auto-generated method stub
out.println(staff.length);
for(Employee e:staff){
writeEmployee(out,e);
}
} private static void writeEmployee(PrintWriter out, Employee e) {
// TODO Auto-generated method stub
GregorianCalendar calendar=new GregorianCalendar();
calendar.setTime(e.getHireDay());
out.println(e.getName()+"|"+e.getSalary()+"|"+calendar.get(Calendar.YEAR)+"|"+
(calendar.get(Calendar.MONTH+1))+"|"+calendar.get(Calendar.DAY_OF_MONTH));
} }
textFile