package io;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
public class DataFileTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker",75000,1987,12,15);
staff[1] = new Employee("Harry Hacker",50000,1988,11,30);
staff[2] = new Employee("John Bush",65000,1989,5,22);
try {
PrintWriter out = new PrintWriter(new FileWriter("employee.dat"));
writeData(staff,out);
out.close();
BufferedReader in = new BufferedReader(new FileReader("employee.dat"));
Employee[] newStaff = readData(in);
in.close();
for(int i=0;i<newStaff.length;i++)
System.out.println(newStaff[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Writes all employees in an array to a print writer
*/
static void writeData(Employee[] e,PrintWriter out){
out.println(e.length);
for(int i=0;i<e.length;i++)
e[i].writeData(out);
}
/**
* Reads an array of employees from a buffered reader
* @throws IOException
* @throws NumberFormatException
*/
static Employee[] readData(BufferedReader in) throws NumberFormatException, IOException{
int n = Integer.parseInt(in.readLine());
Employee[] e = new Employee[n];
for(int i=0;i<n;i++){
e[i] = new Employee();
e[i].readData(in);
}
return e;
}
}
class Employee{
public Employee(){}
public Employee(String n,double s,int year,int month,int day){
name = n;
salary = s;
/*
* GregorianCalendar 与日历操作有关
*/
GregorianCalendar calendar = new GregorianCalendar(year,month-1,day);
hireDay = calendar.getTime();
}
private String name;
private double salary;
private Date hireDay;
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public Date getHireDay(){
return hireDay;
}
public void raiseSalary(double byPercent){
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString(){
return getClass().getName()
+"[name="+name
+",salary="+salary
+",hireDay="+hireDay
+"]";
}
public void writeData(PrintWriter out){
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
out.println(name+"|"
+salary+"|"
+calendar.get(Calendar.YEAR)+"|"
+(calendar.get(Calendar.MONTH)+1)+"|"
+calendar.get(Calendar.DAY_OF_MONTH));
}
public void readData(BufferedReader in) throws IOException{
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s,"|");
name = t.nextToken();
salary = Double.parseDouble(t.nextToken());
int y = Integer.parseInt(t.nextToken());
int m = Integer.parseInt(t.nextToken());
int d = Integer.parseInt(t.nextToken());
GregorianCalendar calendar = new GregorianCalendar(y,m - 1,d);
hireDay = calendar.getTime();
}
}
今天根据java核心技术敲了如上代码,主要介绍了javaIO中的 PrintWriter,该类可对文本内容进行适当排版后再写入文本,同时也了解了一下
GregorianCalendar 类,其主要对日期格式进行处理。