0

I wrote the following code using ObjectOutputStream:

class ClassToTestOutputStream implements Serializable{

    int a;
    String b;

    public ClassToTestOutputStream(){
        a=10;
        b="Deepak";
    }

    public String toString() {

        String s = ""+a+" "+b;
        return s;
    }
}
public class UsingOutputStreams {

    ClassToTestOutputStream ref;
    private ObjectOutputStream oos;

    public UsingOutputStreams(){
    try {
         oos = new ObjectOutputStream(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ref = new ClassToTestOutputStream();
}

public void writeOnScreen(){

    try {
        System.out.println("Writing on Screen");
        oos.writeObject(ref);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    public static void main(String[] args) {

        UsingOutputStreams obj = new UsingOutputStreams();
        obj.writeOnScreen();
    } 
}

And I got answer :

�� Writing on Screen

sr ClassToTestOutputStream����S��M I aL bt Ljava/lang/String;xp
t Deepak

Please help me figure out why such output gets printed.

Community
  • 1
  • 1
Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35

1 Answers1

1

ObjectOutputStream writes Java objects in a form that can be read by ObjectInputStream. The output produced is not intended for human consumption and contains metadata and values in binary form. It is not meant to be human-readable. Attempting to print or display data written to ObjectOutputStream will result in garbage, as you have seen.

You should carefully read the Javadoc for ObjectOutputStream.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190