PrintWriter和Scanner的综合运用写文件并读文件

下用PrinterWriter写入文件,,再用Scanner读文件输出

package textfile;import java.io.*;import java.util.*;public class TextFileTest {(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());}}}(Employee[] emplyoees,PrintWriter out) throws IOException{out.println(emplyoees.length);for(Employee e:emplyoees){writeEmployee(out,e);//写一个元素对象}}(PrintWriter out, Employee e) { out.println(e.getName()+”:”+String.valueOf(e.getBirthyear())+”,”+String.valueOf(e.getBirthmonth())+”,”+String.valueOf(e.getBirthday()));}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;}Employee readEmplyee(Scanner in) {// TODO Auto-generated method stubString 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;}(String name) {this.name = name;}() {return birthyear;}(int birthyear) {this.birthyear = birthyear;}() {return birthmonth;}(int birthmonth) {this.birthmonth = birthmonth;}() {return birthday;}(int birthday) {this.birthday = birthday;}}

每一件事都要用多方面的角度来看它

PrintWriter和Scanner的综合运用写文件并读文件

相关文章:

你感兴趣的文章:

标签云: