首页 > 代码库 > ObjectInputStream
ObjectInputStream
1 package Aug14.IO; 2 3 4 5 import java.io.*; 6 import java.util.*; 7 import java.util.Map.Entry; 8 9 class Student<T> implements Serializable{ 10 private T rollNo; 11 12 Student(T rollNo){ 13 this.rollNo=rollNo; 14 } 15 16 private String Name;int age; 17 18 public void setRollNo(T roll){ 19 rollNo=roll; 20 } 21 22 public T getRollNo(){ 23 return rollNo; 24 } 25 26 public void setName(String roll){ 27 Name=roll; 28 } 29 30 public String getName(){ 31 return Name; 32 } 33 34 public void setAge(int roll){ 35 age=roll; 36 } 37 38 public int getAge(){ 39 return age; 40 } 41 42 public String toString(){ 43 return "Name:- "+getName()+" Age:- "+getAge(); 44 } 45 } 46 47 48 public class StudDataFile { 49 50 private void objectWriter(Map<String, Student<Integer>> m) { 51 try{ 52 File f=new File("D:\\Students.txt"); 53 ObjectOutputStream oos=new ObjectOutputStream( 54 new FileOutputStream(f,true)); 55 oos.writeObject(m); 56 oos.flush(); 57 oos.close(); 58 System.out.println("File Writing Success"); 59 }catch(Exception e){ 60 e.printStackTrace(); 61 } 62 } 63 64 private void objectReader(){ 65 try{ 66 File f=new File("D:\\Students.txt"); 67 ObjectInputStream ois=new ObjectInputStream(new FileInputStream(f)); 68 69 Map<String, Student<Integer>> m=(Map<String, Student<Integer>>)ois.readObject(); 70 71 Set view=m.entrySet(); 72 Iterator it=view.iterator(); 73 while(it.hasNext()) 74 { 75 Map.Entry<String, Student<Integer>> stud = (Entry<String, Student<Integer>>) it.next(); 76 System.out.println("Key:- "+stud.getKey()+"\tValues:- "+stud.getValue()); 77 } 78 ois.close(); 79 }catch(Exception e){ 80 e.printStackTrace(); 81 } 82 System.out.println("File Reading Success"); 83 } 84 85 public static void main(String[] args) { 86 Map<String, Student<Integer>> stuData=http://www.mamicode.com/new HashMap<String, Student<Integer>>(); 87 88 Student<Integer> s; 89 for(int i=0; i<5; i++){ 90 s=new Student<Integer>(i+1); 91 s.setName("Student: "+(i+1)); 92 s.setAge(20); 93 stuData.put("st"+(i+1),s); 94 } 95 96 StudDataFile sf=new StudDataFile(); 97 sf.objectWriter(stuData); 98 sf.objectReader(); 99 }100 101 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。