Java.io.DataOutputStream.writeBytes() Method

Advertisements


Description

The java.io.DataInputStream.writeBytes(String s) method writes a byte to the underlying stream as a 1-byte value. The counter is incremented by 1 on successful execution of this method.

Declaration

Following is the declaration for java.io.DataOutputStream.writeBytes(String s) method:

public final void writeBytes(String s)

Parameters

  • s -- Source as string written as bytes 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.writeBytes(String s) 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;
      String s = "Hello World!!";
      
      try{
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the output stream from the string
         dos.writeBytes(s);
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         System.out.println(s+" in bytes:");
         
         // for each byte in the buffer content
         for(byte b:baos.toByteArray())
         {   
            // print byte
            System.out.print(b + ",");
         }
      }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:

Hello World!! in bytes:
72,101,108,108,111,32,87,111,114,108,100,33,33,



Advertisements
Advertisements