Home » Java programming language

Java ByteArrayOutputStream writeTo() Method with Example

ByteArrayOutputStream Class writeTo() method: Here, we are going to learn about the writeTo() method of ByteArrayOutputStream Class with its syntax and example.
Submitted by Preeti Jain, on March 28, 2020

ByteArrayOutputStream Class writeTo() method

  • writeTo() method is available in java.io package.
  • writeTo() method is used to write the data of this stream to the given OutputStream (os).
  • writeTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • writeTo() method may throw an exception at the time of writing data to the stream.
    IOException: This exception may throw while getting input/output error.

Syntax:

    public void writeTo(OutputStream os);

Parameter(s):

  • OutputStream os – represents the output stream to be written to.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void writeTo(OutputStream os) method of 
// ByteArrayOutputStream

import java.io.*;

public class WriteToOfBAOS {
 public static void main(String[] args) throws Exception {

  byte[] b_arr = {
   97,
   98,
   99,
   100
  };
  
  ByteArrayOutputStream BAOS = null;
  OutputStream out_stm = null;

  try {
   // Instantiates ByteArrayOutputStream and OutputStream
   BAOS = new ByteArrayOutputStream();
   out_stm = new ByteArrayOutputStream();

   // By using write() method is to
   // write b_arr to the BAOS
   BAOS.write(b_arr);

   // By using writeTo() methos is to 
   // write BAOS to the given out_stm
   BAOS.writeTo(out_stm);

   // By using toString() method is 
   // to represent the out_stm as a string
   System.out.print("out_stm.toString(): " + out_stm.toString());

  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   if (BAOS != null)
    BAOS.close();
  }
 }
}

Output

out_stm.toString(): abcd



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.