Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaByteArrayOutputStream writeTo() method in Java with Examples

ByteArrayOutputStream writeTo() method in Java with Examples

The writeTo() method of ByteArrayOutputStream class in Java is used to write the contents of this ByteArrayOutputStream to the specified OutputStream that is passed as the argument. In this method OutputStream is passed as a parameter and the ByteArrayOutputStream is copied to this OutputStream.

Syntax:

public void writeTo(OutputStream outputStr)
             throws IOException

Parameters: This method accepts one parameter outputStr which represents the OutputStream to which the content of ByteArrayOutputStream is to be copied.

Return value: The method does not return any value.

Exceptions: This method throws IOException if an I/O error occurs.

Below programs illustrate writeTo() method in ByteArrayOutputStream class in IO package:

Program 1:




// Java program to illustrate
// ByteArrayOutputStream writeTo() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws Exception
    {
  
        // Create byteArrayOutputStream
        ByteArrayOutputStream byteArrayOutStr
            = new ByteArrayOutputStream();
  
        // Create byte array
        byte[] buf = { 71, 69, 69, 75, 83 };
  
        // Create outputStream
        OutputStream outputStr
            = new ByteArrayOutputStream();
  
        // Write byte array
        // to byteArrayOutputStream
        byteArrayOutStr.write(buf);
  
        // Copy byteArrayOutputStream
        // to OutputStream
        byteArrayOutStr.writeTo(outputStr);
  
        // Print the OutputStream
        System.out.println(
            outputStr.toString());
    }
}


Output:

GEEKS

Program 2:




// Java program to illustrate
// ByteArrayOutputStream writeTo() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create byteArrayOutputStream
        ByteArrayOutputStream byteArrayOutStr
            = new ByteArrayOutputStream();
  
        // Create byte array
        byte[] buf = { 71, 69, 69, 75, 83,
                       70, 79, 82, 71, 69,
                       69, 75, 83 };
  
        // Create outputStream
        OutputStream outputStr
            = new ByteArrayOutputStream();
  
        // Write byte array
        // to byteArrayOutputStream
        byteArrayOutStr.write(buf);
  
        // Copy byteArrayOutputStream
        // to OutputStream
        byteArrayOutStr.writeTo(outputStr);
  
        // Print the OutputStream
        System.out.println(
            outputStr.toString());
    }
}


Output:

GEEKSFORGEEKS

References:
https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#writeTo(java.io.OutputStream)

RELATED ARTICLES

Most Popular

Recent Comments