0

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();

user207421
  • 305,947
  • 44
  • 307
  • 483
vrooom
  • 51
  • 1
  • 11
  • 'If writeInt(65) and write(65) outputs the same data to file': they don't. The outputs are not all the same, and that is why the different methods are provided, and your belief to the contrary is baseless. – user207421 Aug 21 '19 at 12:35
  • then please explain the output "A A A" for 3 different methods – vrooom Aug 21 '19 at 12:37
  • 3
    The output in hex is `0x41 0x00 0x00 0x00 0x41 0x00 0x41`. `DataOutputStream` doesn't produce text files, so everything about this question is wrong, including even your filename. – user207421 Aug 21 '19 at 12:38
  • 1
    https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html Read the javadoc. It explains exaclty what the difference is between the methods. – cameron1024 Aug 21 '19 at 12:41

1 Answers1

4

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:

  • write(int) : Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

  • writeChar(int) : Writes a char to the underlying output stream as a 2-byte value, high byte first.

  • writeInt(int) : Writes an int to the underlying output stream as four bytes, high byte first.

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216