ObjectOutputStream writeObject()方法

java.io.ObjectOutputStream.writeObject(Object obj) 此方法将指定的对象写入ObjectOutputStream。

该对象的类,类的签名,以及类及其所有超类型的非瞬态和非静态字段的值被写入。默认的序列化的类可以使用writeObject和readObject方法被重写。由此对象引用的对象都写及物动词使对象的完全等价的图形可以由ObjectInputStream重建。

1 语法

public final void writeObject(Object obj)

2 参数

obj:要写入的对象。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.ObjectOutputStream.writeObject(Object obj)方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {
        String s = "Hello world!";
        int i = 897648764;

        try {
            // create a new file with an ObjectOutputStream
            FileOutputStream out = new FileOutputStream("test.txt");
            ObjectOutputStream oout = new ObjectOutputStream(out);

            // write something in the file
            oout.writeObject(s);
            oout.writeObject(i);

            // close the stream
            oout.close();

            // create an ObjectInputStream for the file we created before
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

            // read and print what we wrote before
            System.out.println("" + (String) ois.readObject());
            System.out.println("" + ois.readObject());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

Hello world!
897648764

热门文章

优秀文章