What is object serialization?

前端 未结 14 2110
长发绾君心
长发绾君心 2020-11-21 23:23

What is meant by \"object serialization\"? Can you please explain it with some examples?

14条回答
  •  隐瞒了意图╮
    2020-11-22 00:03

    Return the file as an Object : http://www.tutorialspoint.com/java/java_serialization.htm

            import java.io.*;
    
            public class SerializeDemo
            {
               public static void main(String [] args)
               {
                  Employee e = new Employee();
                  e.name = "Reyan Ali";
                  e.address = "Phokka Kuan, Ambehta Peer";
                  e.SSN = 11122333;
                  e.number = 101;
    
                  try
                  {
                     FileOutputStream fileOut =
                     new FileOutputStream("/tmp/employee.ser");
                     ObjectOutputStream out = new ObjectOutputStream(fileOut);
                     out.writeObject(e);
                     out.close();
                     fileOut.close();
                     System.out.printf("Serialized data is saved in /tmp/employee.ser");
                  }catch(IOException i)
                  {
                      i.printStackTrace();
                  }
               }
            }
    
        import java.io.*;
        public class DeserializeDemo
        {
           public static void main(String [] args)
           {
              Employee e = null;
              try
              {
                 FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
                 ObjectInputStream in = new ObjectInputStream(fileIn);
                 e = (Employee) in.readObject();
                 in.close();
                 fileIn.close();
              }catch(IOException i)
              {
                 i.printStackTrace();
                 return;
              }catch(ClassNotFoundException c)
              {
                 System.out.println("Employee class not found");
                 c.printStackTrace();
                 return;
              }
              System.out.println("Deserialized Employee...");
              System.out.println("Name: " + e.name);
              System.out.println("Address: " + e.address);
              System.out.println("SSN: " + e.SSN);
              System.out.println("Number: " + e.number);
            }
        }
    

提交回复
热议问题