下用PrinterWriter写入文件,再用Scanner读文件输出
package textfile;
import java.io.*;
import java.util.*;
public class TextFileTest {
public static void main(String[] args) throws IOException{
Employee[] staff=new Employee[3];
staff[0]=new Employee("张珊珊",1992,12,15);
staff[1]=new Employee("李花花",1993,2,5);
staff[2]=new Employee("丘比特",1995,3,12);
try(PrintWriter out=new PrintWriter("emloyee.txt","UTF-8"))//PrintWriter对象
{
writeData(staff,out);
}
try(Scanner in=new Scanner(new FileInputStream("emloyee.txt"), "UTF-8"))//Scanner对象
{
Employee[] newstaff=readData(in);//读回的数组
for(Employee e:newstaff)
{
System.out.println(e.getName()+":"+e.getBirthyear()+","+e.getBirthmonth()+","+e.getBirthday());
}
}
}
//把emplyoees数组写入到文件中
public static void writeData(Employee[] emplyoees,PrintWriter out) throws IOException
{
out.println(emplyoees.length);
for(Employee e:emplyoees){
writeEmployee(out,e);//写一个元素对象
}
}
//写入一个对象
public static void writeEmployee(PrintWriter out, Employee e) {
out.println(e.getName()+":"+String.valueOf(e.getBirthyear())+","+String.valueOf(e.getBirthmonth())+","+String.valueOf(e.getBirthday()));
}
//从文件中读一个数组
public static Employee[] readData(Scanner in)
{
int n=in.nextInt();
in.nextLine();
Employee[] emplyoees=new Employee[n];
for(int i=0;i<n;i++){
emplyoees[i]=readEmplyee(in);
}
return emplyoees;
}
//读一个对象
public static Employee readEmplyee(Scanner in) {
// TODO Auto-generated method stub
String line=in.nextLine();
String[] info=line.split("[:,]");
String n=info[0];
int y=Integer.parseInt(info[1]);
int m=Integer.parseInt(info[2]);
int d=Integer.parseInt(info[3]);
Employee e=new Employee(n,y,m,d);
return e;
}
}
public class Employee {
String name;
int birthyear,birthmonth,birthday;
Employee(String n,int y,int m,int d ){
name=n;
birthyear=y;
birthmonth=m;
birthday=d;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBirthyear() {
return birthyear;
}
public void setBirthyear(int birthyear) {
this.birthyear = birthyear;
}
public int getBirthmonth() {
return birthmonth;
}
public void setBirthmonth(int birthmonth) {
this.birthmonth = birthmonth;
}
public int getBirthday() {
return birthday;
}
public void setBirthday(int birthday) {
this.birthday = birthday;
}
}