Java - DataOutputStream writeShort(short v) method



Description

The Java DataOutputStream writeShort(short v) method writes a short value to the to the underlying stream as two bytes. The counter written is incremented by 2 on successful invocation of this method.

Declaration

Following is the declaration for java.io.DataOutputStream.writeShort(short v) method −

public final void writeShort(short v)

Parameters

v − a short value to be written to the output stream.

Return Value

The method returns the value of the written field.

Exception

IOException − If an I/O error occurs.

Example - Usage of DataOutputStream writeShort(short v) method

The following example shows the usage of Java DataOutputStream writeShort(short v) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A short[] buf is initialized with some short values. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before. Then short array is iterated to write short values using writeInt() method to the dataoutputstream.

Once short array is fully written into the stream, we've flushed the stream to store the values in the file. Now using FileInputStream and DataInputStream, we're reading the file written earlier. Now we're checking if DataInputStream object has data using available() method. Then using readShort() method, we're reading every value as short. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      FileOutputStream fos = null;
      DataOutputStream dos = null;
      short[] dbuf = {65,66,67,68,69,70};
      
      try {
         // create file output stream
         fos = new FileOutputStream("test.txt");
         
         // create data output stream
         dos = new DataOutputStream(fos);
         
         // for each byte in the buffer
         for (short d:dbuf) {
         
            // write short to the data output stream
            dos.writeShort(d);         
         }
         
         // force bytes to the underlying stream
         dos.flush();
         
         // create file input stream
         is = new FileInputStream("test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // read till end of the stream
         while(dis.available()>0) {
         
            // read short
            short c = dis.readShort();
            
            // print
            System.out.print(c + " ");
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dos!=null)
            is.close();
         if(dis!=null)
            dis.close();
         if(fos!=null)
            fos.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

65 66 67 68 69 70

Example - Usage of DataOutputStream writeShort(short v) method

The following example shows the usage of Java DataOutputStream writeShort(short v) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A short[] buf is initialized with some short values. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before. Then short array is iterated to write short values using writeShort() method to the dataoutputstream.

As a special case, we're closing the stream before writing any value to check if it supports writing values after closing it.

Once short array is fully written into the stream, we've flushed the stream to store the values in the file. Now using FileInputStream and DataInputStream, we're reading the file written earlier. Now we're checking if DataInputStream object has data using available() method. Then using readShort() method, we're reading every value as short. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      FileOutputStream fos = null;
      DataOutputStream dos = null;
      short[] dbuf = {65,66,67,68,69,70};
      
      try {
         // create file output stream
         fos = new FileOutputStream("test.txt");
         
         // create data output stream
         dos = new DataOutputStream(fos);

         // close the stream
         dos.close(); 
		 
         // for each byte in the buffer
         for (short d:dbuf) {
         
            // write short to the data output stream
            dos.writeShort(d);         
         }
         
         // force bytes to the underlying stream
         dos.flush();
         
         // create file input stream
         is = new FileInputStream("test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // read till end of the stream
         while(dis.available()>0) {
         
            // read short
            short c = dis.readShort();
            
            // print
            System.out.print(c + " ");
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dos!=null)
            is.close();
         if(dis!=null)
            dis.close();
         if(fos!=null)
            fos.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

java.io.IOException: Stream Closed
	at java.base/java.io.FileOutputStream.writeBytes(Native Method)
	at java.base/java.io.FileOutputStream.write(FileOutputStream.java:367)
	at java.base/java.io.DataOutputStream.writeShort(DataOutputStream.java:176)
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:32)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.InputStream.close()" because "is" is null
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:62)

As underlying stream FileOutputStream is not supporting write to stream after closing it, we get exception in program execution.

Example - Usage of DataOutputStream writeShort(short v) method

The following example shows the usage of Java DataOutputStream writeShort(short v) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try (FileOutputStream fos = new FileOutputStream("output.dat");
         DataOutputStream dos = new DataOutputStream(fos)) {

         short number = 12345; // Short value
         dos.writeShort(number); // Writes 2 bytes

         System.out.println("Short value written successfully.");

         FileInputStream fis = new FileInputStream("output.dat");
         DataInputStream dis = new DataInputStream(fis);

         short num = dis.readShort(); // Reads 2 bytes as a short
         System.out.println("Read Short: " + num);

      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Short value written successfully.
Read Short: 12345

Explanation

  • FileOutputStream− Creates a binary file "output.dat" for writing.

  • DataOutputStream− Wraps FileOutputStream to enable writing primitive data types.

  • writeShort(short v) Method− Converts 12345 (0x3039 in hexadecimal) into 2 bytes. Stores them in big-endian order−

    • Byte 1(Most Significant Byte): 30

    • Byte 2(Least Significant Byte): 39

Binary Representation (output.dat)

The short 12345 (0x3039) is stored as−

00110000  00111001
java_io_dataoutputstream.htm
Advertisements