125.对象流(ObjectInputStream、ObjectOutputStream)

ObjectOutputStream输出流将对象序列化为字节流进行存储1,ObjectInputStream输入流将读取到的字节流反序列化为对象

ObjectInputStream

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.

可以操作基本数据类型和其它各种对象包括自定义对象2

继承关系
Constructor Summary
ConstructorDescription
protected ObjectInputStream()Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.
ObjectInputStream(InputStream in)Creates an ObjectInputStream that reads from the specified InputStream.
Method Summary
Method Modifier and TypeDescription
int available()Returns the number of bytes that can be read without blocking.
void close()Closes the input stream.
void defaultReadObject()Read the non-static and non-transient fields of the current class from this stream.
protected boolean enableResolveObject(boolean enable)Enables the stream to do replacement of objects read from the stream.
ObjectInputFilter getObjectInputFilter()Returns the serialization filter for this stream.
int read()Reads a byte of data.
int read(byte[] buf, int off, int len)Reads into an array of bytes.
boolean readBoolean()Reads in a boolean.
byte readByte()Reads an 8 bit byte.
char readChar()Reads a 16 bit char.
protected ObjectStreamClass readClassDescriptor()Read a class descriptor from the serialization stream.
double readDouble()Reads a 64 bit double.
ObjectInputStream.GetField readFields()Reads the persistent fields from the stream and makes them available by name.
float readFloat()Reads a 32 bit float.
void readFully(byte[] buf)Reads bytes, blocking until all bytes are read.
void readFully(byte[] buf, int off, int len)Reads bytes, blocking until all bytes are read.
int readInt()Reads a 32 bit int.
String readLine()Deprecated. This method does not properly convert bytes to characters.
long readLong()Reads a 64 bit long.
Object readObject()Read an object from the ObjectInputStream.
protected Object readObjectOverride()This method is called by trusted subclasses of ObjectInputStream that + constructed ObjectInputStream using the protected no-arg constructor.
short readShort()Reads a 16 bit short.
protected void readStreamHeader()The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers.
Object readUnshared()Reads an “unshared” object from the ObjectInputStream.
int readUnsignedByte()Reads an unsigned 8 bit byte.
int readUnsignedShort()Reads an unsigned 16 bit short.
String readUTF()Reads a String in modified UTF-8 format.
void registerValidation(ObjectInputValidation obj, int prio)Register an object to be validated before the graph is returned.
protected Class<?> resolveClass(ObjectStreamClass desc)Load the local class equivalent of the specified stream class description.
protected Object resolveObject(Object obj)This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.
protected Class<?> resolveProxyClass(String[] interfaces)Returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the
void setObjectInputFilter(ObjectInputFilter filter)Set the serialization filter for the stream.
int skipBytes(int len)Skips bytes.

ObjectOutputStream3

继承关系
Constructor Summary

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconstituted on another host or in another process.

Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object’s fields and arrays, and the closure of any other objects referenced from the initial objects.

ConstructorDescription
protected ObjectOutputStream()Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.
ObjectOutputStream(OutputStream out)Creates an ObjectOutputStream that writes to the specified OutputStream.
Method Summary
Method Modifier and TypeDescription
protected void annotateClass(Class<?> cl)Subclasses may implement this method to allow class data to be stored in the stream.
protected void annotateProxyClass(Class<?> cl)Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes.
void close()Closes the stream.
void defaultWriteObject()Write the non-static and non-transient fields of the current class to this stream.
protected void drain()Drain any buffered data in ObjectOutputStream.
protected boolean enableReplaceObject(boolean enable)Enables the stream to do replacement of objects written to the stream.
void flush()Flushes the stream.
ObjectOutputStream.PutField putFields()Retrieve the object used to buffer persistent fields to be written to the stream.
protected Object replaceObject(Object obj)This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.
void reset()Reset will disregard the state of any objects already written to the stream.
void useProtocolVersion(int version)Specify stream protocol version to use when writing the stream.
void write(byte[] buf)Writes an array of bytes.
void write(byte[] buf, int off, int len)Writes a sub array of bytes.
void write(int val)Writes a byte.
void writeBoolean(boolean val)Writes a boolean.
void writeByte(int val)Writes an 8 bit byte.
void writeBytes(String str)Writes a String as a sequence of bytes.
void writeChar(int val)Writes a 16 bit char.
void writeChars(String str)Writes a String as a sequence of chars.
protected void writeClassDescriptor(ObjectStreamClass desc)Write the specified class descriptor to the ObjectOutputStream.
void writeDouble(double val)Writes a 64 bit double.
void writeFields()Write the buffered fields to the stream.
void writeFloat(float val)Writes a 32 bit float.
void writeInt(int val)Writes a 32 bit int.
void writeLong(long val)Writes a 64 bit long.
void writeObject(Object obj)Write the specified object to the ObjectOutputStream.
protected void writeObjectOverride(Object obj)Method used by subclasses to override the default writeObject method.
void writeShort(int val)Writes a 16 bit short.
protected void writeStreamHeader()The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream.
void writeUnshared(Object obj)Writes an “unshared” object to the ObjectOutputStream.
void writeUTF(String str)Primitive data write of this String in modified UTF-8 format. Methods declared in class java.io.OutputStream
测试基本类型和对象的读写
package cn.yzy.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/*
 * ObjectInputStream
 * ObjectOutputStream
 * 对象流
 * 1.写出后读取
 * 2.读写一致
 * 3.可操作基本数据类型和其它各种对象(自定义对象需要实现serializable)
 */
public class objectTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//写出(序列化 serialization)
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
		
		//操作数据(类型)
		oos.writeUTF("编码辛酸泪");
		oos.writeInt(18);
		oos.writeBoolean(false);
		oos.writeChar('b');
		oos.writeObject(new String("谁解其中味"));
		oos.writeObject(new Date());
		Employee emp = new Employee("远哥", 999999.99);
		oos.writeObject(emp);
		oos.flush();
		
		byte[] datas = baos.toByteArray();
		//读取(反序列化 deserialization)
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas))); 
		String msgString = ois.readUTF();
		int integer = ois.readInt();
		Boolean bool = ois.readBoolean();
		char c = ois.readChar();
		
		
		//输出
		System.out.println(msgString);
		System.out.println(integer);
		System.out.println(bool);
		System.out.println(c);
		/*对象数据的还原:可以直接强制类型转换(编译器会报警告)
		 * String str = (String) ois.readObject();
		 * Date d = (Date) ois.readObject();
		 * Employee employee = (Employee) ois.readObject();
		*/
		Object strObj = ois.readObject();
		Object dObj = ois.readObject();
		Object employeeObj = ois.readObject();
		//类型转换要加判断
		if(strObj instanceof String) {
			String str = (String)strObj;
			System.out.println(str);
		}
		if(dObj instanceof Date) {
			Date d = (Date)dObj;
			System.out.println(d);
		}
		if(employeeObj instanceof Employee) {
			Employee employee = (Employee)employeeObj;
			System.out.println(employee);
		}
		
	}
}

//javabean类-->用于封装数据
@SuppressWarnings("serial")
class Employee
	implements java.io.Serializable
{
	private String name;
	private transient double salary; //transient该数据不需要序列化
	public Employee() {
	}
	public Employee(String name, double salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [name=" + name + ", salary=" + salary + "]";
	}
	
}
序列化后存入文件4中,使用的时候再反序列化
package cn.yzy.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/*
 * ObjectInputStream
 * ObjectOutputStream
 * 对象流
 * 1.写出后读取
 * 2.读写一致
 * 3.可操作基本数据类型和其它各种对象(自定义对象需要实现serializable)
 */
public class objectStreamTest02 {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//写出(序列化 serialization)
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("obj.txt")));
		
		//操作数据(类型)
		oos.writeUTF("编码辛酸泪");
		oos.writeInt(18);
		oos.writeBoolean(false);
		oos.writeChar('b');
		oos.writeObject(new String("谁解其中味"));
		oos.writeObject(new Date());
		Employee emp = new Employee("远哥", 999999.99);
		oos.writeObject(emp);
		oos.flush();
		oos.close();
		
		
		//读取(反序列化 deserialization)
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj.txt"))); 
		String msgString = ois.readUTF();
		int integer = ois.readInt();
		Boolean bool = ois.readBoolean();
		char c = ois.readChar();
		
		
		//输出
		System.out.println(msgString);
		System.out.println(integer);
		System.out.println(bool);
		System.out.println(c);
		/*对象数据的还原:可以直接强制类型转换(编译器会报警告)
		 * String str = (String) ois.readObject();
		 * Date d = (Date) ois.readObject();
		 * Employee employee = (Employee) ois.readObject();
		*/
		Object strObj = ois.readObject();
		Object dObj = ois.readObject();
		Object employeeObj = ois.readObject();
		//类型转换要加判断
		if(strObj instanceof String) {
			String str = (String)strObj;
			System.out.println(str);
		}
		if(dObj instanceof Date) {
			Date d = (Date)dObj;
			System.out.println(d);
		}
		if(employeeObj instanceof Employee) {
			Employee employee = (Employee)employeeObj;
			System.out.println(employee);
		}
		ois.close();
	}
}

只有实现了serializable 5接口的类 6,才可以使用ObjectOutPutStream
transient关键字7
透明化之前:
透明化之后:
对象流关系图

  1. 存储到文件、数据库或内存 ↩︎

  2. 加接口serializable ↩︎

  3. 相较于数据流DataOutputStream新增方法 writeObject ↩︎

  4. 文件的后缀可以随意,只要保证读写一致就行,可以是自己随意写的文件后缀如下图: ↩︎

  5. 作用于虚拟机,类似于通行证 ↩︎

  6. 常见的就是用于封装数据的javabean类 ↩︎

  7. 对于javabean类有的数据不需要序列化就将其用transient修饰,使其透明化 ↩︎

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值