Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {

    public static void main(String[] args) throws Exception {
        FileOutputStream out = new FileOutputStream("test.txt");
        ObjectOutputStream oout = new ObjectOutputStream(out);

        oout.writeObject(new Example());
        oout.flush();
        oout.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

        Example a = (Example) ois.readObject();

        System.out.println(a.s);

        a.validateObject();
        ois.close();
    }

}

class Example implements Serializable, ObjectInputValidation {

    String s = "Hello World from java2s.com!";

    private String readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

        ObjectInputStream.GetField gf = in.readFields();

        in.registerValidation(this, 0);

        return (String) gf.get("s", null);
    }

    public void validateObject() throws InvalidObjectException {
        if (this.s.equals("Hello World!")) {
            System.out.println("Validated.");
        } else {
            System.out.println("Not validated.");
        }
    }
}