ObjectOutputStream reset()方法

java.io.ObjectOutputStream.reset() 此方法复位将忽略已经写入流中的任何对象的状态。流中的当前点被标记为reset,因此相应的ObjectInputStream将在同一点被重置。先前写入流中的对象将不会被视为已经存在于流中。它们将再次写入流中。

1 语法

public void reset()

2 参数

3 返回值

4 示例 

package com.yiidian;

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

public class Demo {
    public static void main(String[] args) {
        Object s = "Hello World!";
        Object s2 = "Bye World!";

        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);

            // reset the stream and rewrite what is already written
            oout.reset();

            // write something again
            oout.writeObject(s2);

            // 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 a string
            System.out.println("" + (String) ois.readObject());
            System.out.println("" + (String) ois.readObject());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

Hello World!
Bye World!

热门文章

优秀文章