Java Serializable Class Example

Submitted by code_admin on Tue, 07/17/2018 - 14:03
  1. package metcarob.com.mediaorganiser.mainapp;
  2.  
  3. import java.io.Serializable;
  4.  
  5. import java.util.Date;
  6.  
  7. public class MediaArchive implements Serializable {
  8.     @SuppressWarnings("compatibility:7885778172562393496")
  9.     private static final long serialVersionUID = 1L;
  10.    
  11.     Date m_created = new Date();
  12.  
  13.     public MediaArchive() {
  14.         super();
  15.     }
  16.  
  17.     public Date getCreated() {
  18.         return m_created;
  19.     }
  20. }
  1. package metcarob.com.mediaorganiser.mainapp;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8.  
  9. import java.sql.Connection;
  10. import java.sql.DriverManager;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.sql.Statement;
  14.  
  15. public class _testRunner {
  16.     public _testRunner() throws ClassNotFoundException {
  17.         super();
  18.        
  19.         System.out.println("Start");
  20.        
  21.         MediaArchive ma = new MediaArchive();
  22.            FileOutputStream fileOut = new FileOutputStream("test.arc");
  23.            ObjectOutputStream out = new ObjectOutputStream(fileOut);
  24.            out.writeObject(ma);
  25.            out.close();
  26.             fileOut.close();
  27.             System.out.println("Sucessfully wrot out archive test.arc");
  28.         } catch(IOException i) {
  29.             i.printStackTrace();
  30.         }
  31.  
  32.         MediaArchive readMA = null;
  33.         try
  34.         {
  35.            FileInputStream fileIn = new FileInputStream("test.arc");
  36.            ObjectInputStream in = new ObjectInputStream(fileIn);
  37.            readMA = (MediaArchive)in.readObject();
  38.            in.close();
  39.            fileIn.close();
  40.             System.out.println("Sucessfully read archive test.arc");
  41.         }catch(IOException i)
  42.         {
  43.            i.printStackTrace();
  44.            return;
  45.         }catch(ClassNotFoundException c)
  46.         {
  47.            System.out.println("MediaArchive class not found");
  48.            c.printStackTrace();
  49.            return;
  50.         }
  51.        
  52.         System.out.println("Date from read file was " + readMA.getCreated());
  53.  
  54. }

Tags

RJM Article Type
Quick Reference