java基础--ObjectOutputStream和ObjectInputStream

ObjectOutputStream和ObjectInputStream  

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

 

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

 

看例子

 

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;

 

/**
 * @author 陈静波 E-mail:[email protected]
 * @version 创建时间:Aug 29, 2009 4:06:45 PM 类说明
 */
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修饰的属性不予考虑...很简单的,不举例子了

猜你喜欢

转载自yovi.iteye.com/blog/2269281