PrintWriter和Scanner的综合运用写文件并读文件
生活随笔
收集整理的這篇文章主要介紹了
PrintWriter和Scanner的综合运用写文件并读文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下用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 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;}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;} }總結
以上是生活随笔為你收集整理的PrintWriter和Scanner的综合运用写文件并读文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中Scanner的理解大总结
- 下一篇: java.io,PrintWriter可