- package cn.sjq.Serializable.java;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.OutputStream;
- /**
- * 将 Fruit 对象写入文件
- * @author songjq
- *
- */
- public class JavaSerializableDemo {public static void main(String[] args) throws Exception {
- // 定义水果对象
- Fruit f = new Fruit();
- f.setName("Apple");
- f.setType("001");
- f.setProduction("China");
- /*
- * 将水果对象 f 写入文件 (Fruit 未实现序列化)
- */
- // 定义输出流
- OutputStream out = new FileOutputStream("d:\\temp\\Fruit.ser");
- // 定义对象输出流
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
- objectOutputStream.writeObject(f);
- // 关闭流
- out.close();
- objectOutputStream.close();
- /**
- * 测试结论:
- * 1,Fruit 未实现序列化
- * Exception in thread "main" java.io.NotSerializableException: cn.sjq.Serializable.java.Fruit
- * 说明如果一个对象要被写入文件, 需要对该对象进行序列化
- * 2,Fruit 实现序列化 public class Fruit implements Serializable
- * 对象 Fruit 成功写入了文件 d:\\temp\\Fruit.ser
- */
- /**
- * 反序列化, 将 Fruit.ser 反序列化成 Fruit 对象输出控制台
- */
- InputStream in = new FileInputStream("d:\\temp\\Fruit.ser");
- ObjectInputStream objectInputStream = new ObjectInputStream(in);
- Fruit fruit = (Fruit) objectInputStream.readObject();
- System.out.println(f.getName()+"\t"+f.getType()+"\t"+f.getProduction());
- /*
- * 输出结果:
- * Apple 001 China
- */
- }
- }
- package cn.sjq.Serializable.java;
- import java.io.Serializable;
- /**
- * Java 序列化: 如果一个类实现了 Java 序列化, 这个类就可以作为输入输出对象
- * 定义一个 JAVA Bean Fruit
- * @author songjq
- *
- */
- public class Fruit implements Serializable {
- private String name;
- private String type;
- private String production;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getProduction() {
- return production;
- }
- public void setProduction(String production) {
- this.production = production;
- }
- }
来源: http://www.bubuko.com/infodetail-2699294.html