Java.io.DataOutputStream.write() Method

Advertisements


Description

The java.io.BufferedInputStream.write(byte[] b, int off, int len) method writes len bytes from the specified byte array b starting at position off to the underlying output stream.

Declaration

Following is the declaration for java.io.DataOutputStream.write(byte[] b, int off, int len) method:

public void write(byte[] b, int off, int len)

Parameters

  • b -- The source buffer.

  • off -- The start position off.

  • len -- The number of bytes to write to the stream.

Return Value

This method does not return any value.

Exception

  • IOException -- if an I/O error occurs.

Example

The following example shows the usage of java.io.DataOutputStream.write(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
         
      ByteArrayOutputStream baos = null;
      DataOutputStream dos = null;
      byte[] buf = {87,64,72,31,90};
      
      try{
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the stream from the source buffer
         dos.write(buf, 2, 3);
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray())
         {
            System.out.println(b);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(dos!=null)
            dos.close();
         if(baos!=null)
            baos.close();
      }
   }
}

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

72
31
90



Advertisements
Advertisements