集合資料寫入檔案
阿新 • • 發佈:2018-11-09
package jihe; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import listtomap.Student; public class collection { public static void main(String[] args) { // TODO Auto-generated method stub Set<Student> set = new TreeSet<Student>(); Scanner in=new Scanner(System.in); while(true) { System.out.println("請輸入資訊:"); String str=in.next(); if("exit".equals(str)) { break; } String [] arr=str.split("#"); int sno=Integer.parseInt(arr[0]); String name=arr[1]; int age=Integer.parseInt(arr[2]); Student stu=new Student(sno,name,age); set.add(stu); } Writer w; PrintWriter pw=null; try { pw=new PrintWriter(new FileWriter("e:/abcd")); for(Student stu:set) { String str=stu.getSno()+" "+stu.getName()+" "+stu.getAge(); pw.println(str);//一行一行往檔案中寫,和pw.writer()不一樣 } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { pw.close(); } } }