分享java的Serializable功能

可以将java对象序列化为文件,也可以将文件反序列化为java对象

原创不易,转载请注明出处:分享java的Serializable功能

DeserializeFile2Object.java

package com.zuidaima.util;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * 反序列化文件到java对象
 * 
 * @author javaniu
 * 
 */
public class DeserializeFile2Object {

	public static void main(String[] args) {
		Address address = deserialzeAddress();
		System.out.println(address);
	}

	public static Address deserialzeAddress() {

		Address address;

		try {

			FileInputStream fin = new FileInputStream("c:/address.ser");
			ObjectInputStream ois = new ObjectInputStream(fin);
			address = (Address) ois.readObject();
			ois.close();

			return address;

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

}

	    			


SerializeObject2File.java

package com.zuidaima.util;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化java对象到文件
 * 
 * @author javaniu
 * 
 */
public class SerializeObject2File {

	public static void main(String args[]) {
		serializeAddress("北京朝阳区", "中国");
	}

	public static void serializeAddress(String street, String country) {

		Address address = new Address();
		address.setStreet(street);
		address.setCountry(country);

		try {

			FileOutputStream fout = new FileOutputStream("c:\\address.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fout);
			oos.writeObject(address);
			oos.close();
			System.out.println("Done");

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

	    			

代码下载地址: http://www.zuidaima.com/share/1550463266802688.htm



你可能感兴趣的:(java,Serializable,对象,序列化)