简体   繁体   中英

Why Bytes written by writeByte() of DataOutputStream and writeByte() of ObjectOutputStream are different?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM