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.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;

public class Main implements Serializable {

    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.isDefault);

        System.out.println(a.string);

        ois.close();
    }

}

class Example implements Serializable {

    String string = "Hello World!";
    boolean isDefault;

    private static final ObjectStreamField[] serialPersistentFields = {
            new ObjectStreamField("string", String.class) };

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

        ObjectInputStream.GetField fields = in.readFields();

        isDefault = fields.defaulted("string");
        string = (String) fields.get("string", null);
    }

    private void writeObject(ObjectOutputStream out) throws IOException {

        ObjectOutputStream.PutField fields = out.putFields();
        fields.put("string", string);
        out.writeFields();

    }
}