序列化与普通存储有什么区别?是说只有implements Serializable后才能使用对象流(ObjectOutputStream)么?

解决方案 »

  1.   

    import java.io.*;class Test_Object
    {
    public static void main(String[] args)
    {
    try
    {
    staff e1 = new staff("Jiang",18);
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
    out.writeObject(e1);
    out.close();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }


    }class staff implements Serializable
    {
    private String name;
    private int age;

    public staff(String name,int age)
    {
    this.name=name;
    this.age=age;
    }

    public String getname()
    {
    return this.name;
    }

    public int getage()
    {
    return this.age;
    }
    }这段程序假如把implements Serializable注释的话,也会输出一个文本,但内容相差很多,这两者的区别究竟是因为什么呢?
      

  2.   

    序列化 是为了在不同的进程中传递数据
    不实现Serializable的话,你的数据无法在两个进程间共享。也无法写磁盘等
      

  3.   

    import java.io.*;
    import java.util.*;
    public class Ex_1
    {
    public static void main(String[] args) throws Exception
    {
    Scanner in = new Scanner(System.in);
    String name = in.nextLine();
    Employee e1 = new Employee(name,21,100);
    RandomAccessFile ra = new RandomAccessFile("1.txt","rw"); 
    ra.write(e1.name.getBytes());
    // int result = (int)e1.Computation();
    e1.ToString();
    //ra.write(result);
    ra.close();
    }
    }
    class Employee
    {
    public String name = null;
    public int age = 0;
    public double salary = 0;

    public Employee(String n,int a,double s)
    {
    this.name = n;
    this.age = a;
    this.salary = s;
    }

    public double Computation()
    {
    return Math.pow(this.salary,2);

    }

    public void ToString()
    {
    System.out.println(this.name +" "+ this.age + " " + this.salary);
    }
    }这样不是也写磁盘了么?