JavaIO<4>--ObjectInputStream和ObjectOutputStream
JavaIO<4>--ObjectInputStream和ObjectOutputStream
Zhao-Qian 发表于3年前
JavaIO<4>--ObjectInputStream和ObjectOutputStream
  • 发表于 3年前
  • 阅读 21
  • 收藏 0
  • 点赞 0
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

摘要: 学习ObjectInputStream 和 ObjectOutputStream

ObjectInputStream 和 ObjectOutputStream 介绍

ObjectInputStream 和 ObjectOutputStream 的作用是,对基本数据和对象进行序列化操作支持
创建“文件输出流”对应的ObjectOutputStream对象,该ObjectOutputStream对象能提供对“基本数据或对象”的持久存储;当我们需要读取这些存储的“基本数据或对象”时,可以创建“文件输入流”对应的ObjectInputStream,进而读取出这些“基本数据或对象”。
注意: 只有支持 java.io.Serializable 或 java.io.Externalizable 接口的对象才能被ObjectInputStream/ObjectOutputStream所操作!

ObjectOutputStream 函数列表

// 构造函数 ObjectOutputStream(OutputStream output) // public函数 void close() void defaultWriteObject() void flush() ObjectOutputStream.PutField putFields() void reset() void useProtocolVersion(int version) void write(int value) void write(byte[] buffer, int offset, int length) void writeBoolean(boolean value) void writeByte(int value) void writeBytes(String value) void writeChar(int value) void writeChars(String value) void writeDouble(double value) void writeFields() void writeFloat(float value) void writeInt(int value) void writeLong(long value) final void writeObject(Object object) void writeShort(int value) void writeUTF(String value) void writeUnshared(Object object) 
ObjectInputStream 函数列表

// 构造函数 ObjectInputStream(InputStream input) int available() void close() void defaultReadObject() int read(byte[] buffer, int offset, int length) int read() boolean readBoolean() byte readByte() char readChar() double readDouble() ObjectInputStream.GetField readFields() float readFloat() void readFully(byte[] dst) void readFully(byte[] dst, int offset, int byteCount) int readInt() String readLine() long readLong() final Object readObject() short readShort() String readUTF() Object readUnshared() int readUnsignedByte() int readUnsignedShort() synchronized void registerValidation(ObjectInputValidation object, int priority) int skipBytes(int length)

演示程序

package org.credo.jdk.io.ObjectStreamTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class ObjectStreamTest
{

	public static void main(String[] args)
	{
		try
		{
			testWrite();
			testRead();
		} catch (IOException | ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	private static final String TMP_FILE = "computer.tmp";
	

	public static void testWrite() throws FileNotFoundException, IOException
	{
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(TMP_FILE));
		out.writeBoolean(true);
		out.writeByte((byte) 65);
		out.writeChar('a');
		out.writeInt(20131015);
		out.writeFloat(3.14F);
		out.writeDouble(1.414D);
		// 写入HashMap对象  
        HashMap<String,String> map = new HashMap<>();  
        map.put("one", "red");  
        map.put("two", "green");  
        map.put("three", "blue");  
        out.writeObject(map);  
        // 写入自定义的Computer对象,Computer实现了Serializable接口  
        Computer computer=new Computer(1, 5666.66, "Y480");
        out.writeObject(computer);
        out.close();
	}
	
	@SuppressWarnings("rawtypes")
	public static void testRead() throws FileNotFoundException, IOException, ClassNotFoundException
	{
		ObjectInputStream in=new ObjectInputStream(new FileInputStream(TMP_FILE));
		System.out.printf("boolean:%b\n" , in.readBoolean());  
        System.out.printf("byte:%d\n" , (in.readByte()&0xff));  
        System.out.printf("char:%c\n" , in.readChar());  
        System.out.printf("int:%d\n" , in.readInt());  
        System.out.printf("float:%f\n" , in.readFloat());  
        System.out.printf("double:%f\n" , in.readDouble());
        
        // 读取HashMap对象  
        HashMap map = (HashMap) in.readObject();
        Iterator iterator=map.entrySet().iterator();
        while (iterator.hasNext())
		{
			Map.Entry mapEntry = (Map.Entry) iterator.next();
			System.out.printf("%-6s -- %s\n" , mapEntry.getKey(), mapEntry.getValue());
		}
        
        //读取Computer
        Computer computer=(Computer)in.readObject();
        System.out.println("computer: " + computer);
        in.close();
	}

}

class Computer implements Serializable
{

	private static final long serialVersionUID = -6347513352513264586L;

	private int id;
	private double price;
	private String name;
	
	public Computer(int id,double price,String name) {
		this.id=id;
		this.price=price;
		this.name=name;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public double getPrice()
	{
		return price;
	}

	public void setPrice(double price)
	{
		this.price = price;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	@Override
	public int hashCode()
	{
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public boolean equals(Object obj)
	{
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public String toString()
	{
		return ToStringBuilder.reflectionToString(this);
	}

}

输出

boolean:true
byte:65
char:a
int:20131015
float:3.140000
double:1.414000
three  -- blue
two    -- green
one    -- red
computer: org.credo.jdk.io.ObjectStreamTest.Computer@4935b92e[id=1,price=5666.66,name=Y480]


共有 人打赏支持
粉丝 307
博文 156
码字总数 238058
×
Zhao-Qian
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: