首页 > 代码库 > 程序猿浅谈JAVA的序列化
程序猿浅谈JAVA的序列化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.io.Serializable; public class Person implements Serializable{ private static final long serialVersionUID = 1L; public String name; public int age; public double money; private static final long serialVersionUID = 1L; public Person(String name, int age, double money) { this .name = name; this .age = age; this .money = money; } @Override public String toString() { return "name is:" +name+ " , age is:" +age+ " , money is:" +money; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class DemoText01 { public static void main(String[] args) { Person person = new Person( "joinName" , 20 , 100.89 ); //序列化对象 -->只有可序列化的类,对象才能序列化 try { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "d:/save.txt" )); oos.writeObject(person); System.out.println( "保存对象" ); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class DemoText02 { public static void main(String[] args) { try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "d:/save.txt" )); Person person = (Person) ois.readObject(); System.out.println(person); ois.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
欢迎大家访问我的个人网站 萌萌的IT人
程序猿浅谈JAVA的序列化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。