欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/3/20 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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的综合运用写文件并读文件的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。