zoukankan      html  css  js  c++  java
  • JAVA序列化在IO中读写对象的使用

    序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。

    序列化的实现:将需要被序列化的类实现Serializable接口,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。

    写对象和读对象的时候一定要使用序列化:

    import java.io.*;
    
    class Product implements Serializable {
    	private static final long serialVersionUID = 1L;
    	private float price;
    	private float tax;
    	public Product(float price) {
    		this.price = price;
    		tax = (float)(price*0.20);
    	}
    	public String toString() {
    		return "price:"+price+",tax:"+tax;
    	}
    }
    
    public class CmdDemo {
    
    	public static void main(String[] str) throws Exception {
    		Product p1 = new Product(100);
    		ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("d:\product.txt"));
    		os.writeObject(p1);
    		os.close();
    		ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\product.txt"));
    		Product p2 = (Product) is.readObject();
    		System.out.println(p2.toString());
    	}
    }
    
  • 相关阅读:
    对我比较有用的网站
    ubuntu各种安装
    arabaraba
    镜像源相关
    硬盘相关
    python模块
    递归和循环两种方式实现未知维度集合的笛卡尔积
    单例模式的两种实现方式
    经典String str = new String("abc")内存分配问题
    js方法的命名不能使用表单元素的名称或ID
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3318158.html
Copyright © 2011-2022 走看看