ObjectOutputStream和ObjectInputStream

来源:互联网 发布:中国电信网络电视 编辑:程序博客网 时间:2024/05/10 07:56

这个流的作用是,直接将一个对象转换为字节流..其实就是序列化...implements Serializable

Serializable这个是标记性的接口...标记性就是说,这个接口没有提供任何的方法.所以我们也不需要实现方法.但是如果某一个类需要被序列化,那么,他就必须实现这个接口...

  DataInputStream和DataOutputStream  多线程介绍ObjectOutputStream和ObjectInputStream  2009-08-29 16:30:20|  分类: JAVA基础 |  标签: |字号大中小 订阅 这个流的作用是,直接将一个对象转换为字节流..其实就是序列化...implements SerializableSerializable这个是标记性的接口...标记性就是说,这个接口没有提供任何的方法.所以我们也不需要实现方法.但是如果某一个类需要被序列化,那么,他就必须实现这个接口...看例子package com.test.Stream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.Serializable;import java.io.FileOutputStream;import java.io.ObjectOutputStream;import java.io.FileInputStream;import java.io.ObjectInputStream;public class ObjectStreamTest{ public static void main(String[] args) {  T t = new T();  t.k = 15;  try  {   FileOutputStream fos = new FileOutputStream("d:/333.txt");   ObjectOutputStream oos = new ObjectOutputStream(fos);   oos.writeObject(t);   fos.close();   oos.close();  } catch (FileNotFoundException e)  {   e.printStackTrace();  } catch (IOException e)  {   e.printStackTrace();  }    try  {   FileInputStream fis = new FileInputStream("d:/333.txt");   ObjectInputStream ois = new ObjectInputStream(fis);      T t2 = (T)ois.readObject();      System.out.println(t2.i);   System.out.println(t2.k);   System.out.println(t2.s);   System.out.println(t2.j);  } catch (FileNotFoundException e)  {   e.printStackTrace();  } catch (IOException e)  {   e.printStackTrace();  } catch (ClassNotFoundException e)  {   e.printStackTrace();  } }}@SuppressWarnings("all")class T implements Serializable{ int i = 20; short j = 10; String s = "hello"; int k = 100;}

注意,这里虽然将Object写到了333.txt文件中.但是我们可以看到.333.txt文件里的内容我们看不懂

最后说下一个关键字..transient 这个表示透明的,只能修饰类里的属性...作用是,在序列化的时候对被transient修饰的属性不予考虑...

0 0
原创粉丝点击