joi, 18 iunie 2015

Java: Sample of Serialization

//Serializable is in java.io package
import java.io.*;

//Serializable a way to say that this type is OK to be serialized
// Used to save the object state
public class SerializationTest implements Serializable {
    private int width; 
    private int height; 
    //transient says "don't save me"
    transient String name; 
    
    public void setWidth(int value) {
        width = value;
    }
    
    public void setHeight(int value) {
        height = value;
    }
    
    public int getWidth() {
        return width;
    }
    
    public static void main(String[] args) {
        SerializationTest test = new SerializationTest();
        test.setWidth(10);
        test.setHeight(20);
        
        try { // I/O can throw exceptions
            //Connect to a file (FileOutputStream is a connection stream. In this case to a file)
            FileOutputStream fs = new FileOutputStream("test.ser");
            //Make an ObjectOutputStream chained to the connection stream
            ObjectOutputStream os = new ObjectOutputStream(fs);
            //write the object
            os.writeObject(test);
            os.close();
            
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.ser"));
            //You read objects In (using readObjeet()) in the order In which they were originally written.
            //return type is an Object
            //static variables are not serialized
            SerializationTest restored = (SerializationTest) is.readObject();
            
            System.out.println("Restored type: \t" + restored.getWidth());
            
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        
        File myfile = new File("test.ser");
        System.out.println("File exists? : \t" + myfile.exists());
        System.out.println("\tAbsolute path:: \t" + myfile.getAbsolutePath());
    }
    
    
}

Niciun comentariu:

Trimiteți un comentariu