zoukankan      html  css  js  c++  java
  • 自定义序列化

    package File;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.io.IOException;
    public class SerializeTest {
    	public static void main(String[] args) {
    		try (ObjectOutputStream oos = new ObjectOutputStream(
    				new FileOutputStream("transient.txt"));
    				ObjectInputStream ois = new ObjectInputStream(
    						new FileInputStream("transient.txt"))) {
    			Person per = new Person("孙悟空", 500);
    			oos.writeObject(per);
    			Person p = (Person) ois.readObject();
    			System.out.println(p.getName());//输出空悟孙
    			System.out.println(p.getAge());//输出501
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    class Person implements Serializable {           //序列化的类必须实现Serializable或Externalizable接口
    	private String name;
    	private transient int age;//transient表示不进行不序列化
    
    	public Person(String name, int age) {
    		this.name = name;
    		this.age = age;
    	}
    
    	public String getName() {
    		return this.name;
    	}
    
    	public int getAge() {
    		return this.age;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	/*进行自定义序列化,要在序列化的类中添加两个方法,都是private,这里用到了反射*/
    	
    	private void writeObject(ObjectOutputStream out)throws IOException
    	{
    		out.writeObject(new StringBuffer(name).reverse());
    		out.writeInt(age);
    	}
    	private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException
    	{
    		this.name = ((StringBuffer)in.readObject()).toString();
    		this.age = in.readInt()+1;
    	}
    }
    
  • 相关阅读:
    ssh或scp到远程电脑,不用输密码
    关于浏览器缓存,cookie , session
    js小tips和小笔记
    Promise对象
    terminal命令
    喜大普奔:我的个人博客www.yxmblog.top
    TCP/UDP常用端口号
    以后可能在博客园写的少了!
    << 转载>>Shell一些强大的命令
    Linux下的简单压缩相关操作
  • 原文地址:https://www.cnblogs.com/masterlibin/p/4788510.html
Copyright © 2011-2022 走看看