您的位置:首页 > 移动开发 > Objective-C

java语言编程IO流之对象序列化和ObjectInputStream与ObjectOutputStream

2015-03-21 22:35 627 查看
import java.io.*;
public class TestObjectStream { public static void main(String[] args) {  T t = new T();  t.name = "jay chou";  FileOutputStream fos = null;  ObjectOutputStream oos = null;  FileInputStream fis = null;  ObjectInputStream ois = null;  try {    fos= new FileOutputStream("D:\\bak\\test.dat");    oos = new ObjectOutputStream(fos);    oos.writeObject(t);    oos.writeDouble(0.1);    oos.flush();//不加这一句,有可能出现异常java.io.EOFException        fis = new FileInputStream("D:\\bak\\test.dat");    ois = new ObjectInputStream(fis);    T tt = (T)ois.readObject();    double d = ois.readDouble();    System.out.println(tt);    System.out.println(d);  } catch (IOException e) {    e.printStackTrace();    }catch (ClassNotFoundException e) {    e.printStackTrace();   } finally {   try {     ois.close();     fis.close();     oos.close();     fos.close();    } catch (IOException e) {     e.printStackTrace();    }       }  }}
class T implements Serializable {//必须实现该接口,才可使用户自定义类可以序列化 String name = "jay"; transient int i = 7; long t = 10L; double d = Math.random(); char c = 'a';  public String toString() {  return ("name " + name + " i: " + i + " t:" + t + " d: " + d + " c: " + c); }}/*D:\java\io>javac TestObjectStream.java
D:\java\io>java TestObjectStreamname jay chou i: 7 t:10 d: 0.7328874131779102 c: a0.1
=====================================================
D:\java\io>javac TestObjectStream.java
D:\java\io>java TestObjectStreamname jay chou i: 0 t:10 d: 0.43315260736775785 c: a0.1
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐