Java.io.DataOutputStream.write() Method

Advertisements


Description

The java.io.BufferedInputStream.write(int b) method writes the specified source byte to the underlying output stream. The counter written is incremented by 1 on successful invocation.

Declaration

Following is the declaration for java.io.DataOutputStream.write(int b) method:

public void write(int b)

Parameters

  • b -- The source byte as integer.

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(int b) 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;
      int[] buf = {65, 66, 67, 68, 69, 70, 71};
      
      try{
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the stream from integer array
         for(int i: buf)
         {
            dos.write(i);
         }
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray())
         {
            // convert byte to char
            char c = (char)b;
            
            // print character
            System.out.print(c);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(baos!=null)
            baos.close();
         if(dos!=null)
            dos.close();
      }
   }
}

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

ABCDEFG



Advertisements
Advertisements