javafiledataoutputstream

why does Java DataOutputStream Class provide write() , writeInt() when all outputs the same thing


A data output stream class claims to write primitive Java data types to an output stream in a portable way.And it provides writeInt and other methods for their respective datatypes but if writeInt(65) and write(65) outputs the same data to file then what is the difference and use of writeInt

   FileOutputStream file = new FileOutputStream("D:\\newfile.txt");  
   DataOutputStream data = new DataOutputStream(file);  
   data.write(65);
   data.writeInt(65);
   data.writeChar(65);
   data.flush();  
   data.close();  

I expect the output as A 65 A, but the actual output is A A A.

I know if we have to output integer as 65 we have to use write(65+"") but then what is the use of writeInt();


Solution

  • You are mistaken about the output. In fact ... according to the javadoc ... the output will be the following 7 byte sequence

    0x41 0x00 0x00 0x00 0x41 0x00 0x41
    

    When you write that to a text console (with UTF-8 or Latin-1 as the character encoding) the 0x41's render as A and the 0x00 values are NUL control characters. NUL is a non-printing character and ... naturally ... you can't see it.

    So, it renders as AAA on a typical console. But that is misleading you.

    You can see this more clearly if you run your Java snippet like this (on Linux, Unix, and probably MacOS too)

     java YourDemoApp 
     od -x yourOutputFile
    

    Your real problem is that you misunderstand the purpose of DataOutputStream and (by implication) DataInputStream. Their purpose is to write Java data values in binary form and then read them back. For example:

    See the javadoc for more details.

    The output of DataOutputStream is not intended to be read using a text editor or written to a console. (If that is your intention, you should be using a Writer or a PrintWriter.)