ByteArrayOutputStream toByteArray() method in Java with Examples
Last Updated :
28 May, 2020
The toByteArray() method of ByteArrayOutputStream class in Java is used to create a newly allocated byte array. The size of the newly allocated byte array is equal to the current size of this output stream. This method copies valid contents of the buffer into it.
Syntax:
public byte[] toByteArray()
Parameters: This method does not accept any parameter.
Return value: The method returns newly allocated byte array which has the valid contents of this output stream.
Exceptions: This method does not throw any exception.
Below programs illustrate toByteArray() method in ByteArrayOutputStream class in IO package:
Program 1:
import java.io.*;
public class GFG {
public static void main(String[] args)
throws Exception
{
ByteArrayOutputStream byteArrayOutStr
= new ByteArrayOutputStream();
byte [] buf = { 71 , 69 , 69 , 75 , 83 };
byteArrayOutStr.write(buf);
for ( byte b : byteArrayOutStr
.toByteArray()) {
System.out.println(( char )b);
}
}
}
|
Program 2:
import java.io.*;
public class GFG {
public static void main(String[] args)
throws Exception
{
ByteArrayOutputStream byteArrayOutStr
= new ByteArrayOutputStream();
byte [] buf = { 71 , 69 , 69 , 75 , 83 ,
70 , 79 , 82 , 71 , 69 ,
69 , 75 , 83 };
byteArrayOutStr.write(buf);
for ( byte b : byteArrayOutStr
.toByteArray()) {
System.out.println(( char )b);
}
}
}
|
Output:
G
E
E
K
S
F
O
R
G
E
E
K
S
References:
https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...