Java.io.ObjectOutputStream useProtocolVersion() 方法
描述
java.io.ObjectOutputStream.useProtocolVersion(int version) 方法指定写入流时使用的流协议版本。
此例程提供了一个挂钩,使当前版本的序列化能够以向后兼容的流格式的先前版本的格式写入。
声明
以下是 java.io.ObjectOutputStream.useProtocolVersion() 方法的声明。
public void useProtocolVersion(int version)
参数
version − 使用 java.io.ObjectStreamConstants 中的 ProtocolVersion。
返回值
此方法不返回值。
异常
IllegalStateException − 如果在任何对象被序列化后调用。
IllegalArgumentException − 如果传入无效版本。
IOException − 如果发生 I/O 错误
示例
下面的例子展示了 java.io.ObjectOutputStream.useProtocolVersion() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class ObjectOutputStreamDemo {
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);
// change protocol version
oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_1);
// write something in the file
oout.writeObject(s);
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!

