Java Binary Input and Output


Java Binary Input and Output:

Java provides two types of streams to address binary input and output operations.

Data Streams:
  • Data stream API supports binary input/output of Java Primitive data types (boolean, char, byte, short, int, long, float, and double) and String values. 

  • Java provides two important interface for Data Streams – DataInput & DataOutput.  And the classes implementing these interfaces are – DataInputStream & DataOutputStream respectively.

Data type                  Output Method                                    Input Method

double                  DataOutputStream.writeDouble            DataInputStream.readDouble
int                         DataOutputStream.writeInt                   DataInputStream.readInt
String                    DataOutputStream.writeUTF               DataInputStream.readUTF

  • DataOutputStream or DataInputStream can only be created as a wrapper for an existing byte stream object.

Sample Code snippet to use above described methods:

  • In each write operation on DataOutputStream, data will be serialized into binary format and in each read operation, data is being de-serialized from binary format.

  • DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value.

Object Streams:
  • Similar to Data Streams, Object streams support binary I/O of objects. All these classes implement Serializable interface.

  • ObjectInput and ObjectOutput interaces are sub interfaces of DataInput and DataOutput interfaces respectively.

  • Basic implementations of above two interfaces are – ObjectInputStream & ObjectOutputStream respectively.

  • An object stream can contain a mixture of primitive and object values.

 Sample Code snippet using writeObject() and readObject() methods.


Profile photo of Siva

About Siva

Senior Hadoop developer with 4 years of experience in designing and architecture solutions for the Big Data domain and has been involved with several complex engagements. Technical strengths include Hadoop, YARN, Mapreduce, Hive, Sqoop, Flume, Pig, HBase, Phoenix, Oozie, Falcon, Kafka, Storm, Spark, MySQL and Java.

Leave a comment

Your email address will not be published. Required fields are marked *