黑马程序员-学习对象序列化日记

来源:互联网 发布:如何举报淘宝卖家 编辑:程序博客网 时间:2024/05/18 13:04

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

/*---------------------------------------------------ObjecStreamDemo.java--------------------------------------------------------------------------------*/ 


package heimaLog;
import java.io.*;
/*
 * 打印流 : PrintWriter与PrintStream 可以直接操作输出流和文件
 * 序列流: SequenceInputStream  对多个流进行合并
 * 操作对象:ObjectInputStream与ObjectOutputStream 被操作的对象需要实现Serializable(标记接口)
 *        读取存储文件的对象  对象的持久化存储(找一个介质能长期保存数据)对象的序列化,对象的可串连性,
 *        
 * 
 * */
public class ObjecStreamDemo {
 
 public static void main(String[] args)throws IOException,ClassNotFoundException
 {
  
  //writeOb();
  readOb();
  
 }
 public static void readOb() throws IOException, ClassNotFoundException
 {
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
  
  Person p = (Person)ois.readObject();
  System.out.println(p);
  ois.close();
  
 }
 public static void writeOb() throws IOException
 {
  ObjectOutputStream oos =
                   new ObjectOutputStream(new FileOutputStream("obj.txt"));
  
  oos.writeObject(new Person("lisi",39,"en"));
  oos.close();
 }
}
/* ----------------------------------------------------Person.java----------------------------------------------------------------------------------------------*/

package heimaLog;
/*没有方法的接口通常称为标记性接口*/
import java.io.*;
 class Person implements Serializable{
 public static final long serialVersionUID = 43L;
 
 private String name;//改变类后Serializable定义的标记会不同
 transient int age;  //如果想要非静态成员也不被序列化 可以加入transient 关键字
 static String country = "cn"; //当成员定义为静态时将不会被序列化
 Person(String name,int age,String country){
  
  this.name = name;
  this.age=age;
  this.country = country;
  
 }
 
 public String toString()
 {
  return name+":"+age;
  
  
 }
}
 


---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

0 0