1

As the purpose of writeByte() is same in both classes. But both are writing different contents.

import java.io.*;
class First
{
        public static void main(String[] args) throws IOException
        {
                FileOutputStream fos = new FileOutputStream("b.txt");
Line 1:         ObjectOutputStream oos = new ObjectOutputStream(fos);
Line 2:         DataOutputStream oos = new DataOutputStream(fos);
                oos.writeByte(65);
                oos.close();
                FileInputStream fis = new FileInputStream("b.txt");
                int x=0;
                System.out.println("Output");
                while((x=fis.read())!=-1)
                {
                        System.out.println(x);
                }
                fis.close();
        }
}

If Line 1 is commented out, output is:

65

If Line 2 is commented out, output is:

172
237
0
5
119
1
65

Why this difference?

my name is GYAN
  • 1,269
  • 13
  • 27
  • 4
    Read the last paragraph of [ObjectOutputStream Javadoc](https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html). On top of that, your code is missing all the necessary `close` statements. – Marko Topolnik Oct 05 '16 at 13:32
  • 1
    There should be more output than that. The `ObjectOutputStream` should start with 0xAC and the rest of the stream header, and terminate with your byte of 65. You've forgotten to close the output stream. – user207421 Oct 05 '16 at 14:07
  • @EJP Thanks, I corrected it. – my name is GYAN Oct 06 '16 at 04:30

1 Answers1

3

Object Streams are for writing objects. This means it has formatting information to say what you wrote as well as the data you wrote. Object Streams also has a header at the start which checks the data is an Object Stream.

Data Streams only write the data you asked it to. There is no extra information.

BTW If you want to see what is written to a Stream you can write to a ByteArrayOutputStream and call toByteArray() when you have finished. No need to write it to a file you have to read back.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130