ByteArrayOutputSteam close() method in Java with Examples
Last Updated :
28 May, 2020
The close() method of ByteArrayOutputStream class in Java has no effect if other methods of this class are called after closing the ByteArrayOutputStream. This method does not throw exception if even after closing the ByteArrayOutputStream, the other method is called.
Syntax:
public void close()
Specified By: This method is specified by close() method of AutoCloseable interface and close() method of Closeable interface.
Overrides:This method overrides close() method of OutputStream class.
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exceptions: This method does not throw any exception.
Below programs illustrate close() method in ByteArrayOutputStream class in IO package:
Program 1:
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
try {
ByteArrayOutputStream byteArrayOutStr
= new ByteArrayOutputStream();
byte [] buf = { 71 , 69 , 69 , 75 , 83 };
byteArrayOutStr.close();
byteArrayOutStr.write(buf);
System.out.println(
byteArrayOutStr.toString());
}
catch (Exception e) {
System.out.println(
"ByteArrayOutputStream is closed" );
}
}
}
|
Program 2:
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
try {
ByteArrayOutputStream byteArrayOutStr
= new ByteArrayOutputStream();
byte [] buf1 = { 71 , 69 , 69 , 75 , 83 };
byte [] buf2 = { 70 , 79 , 82 };
byteArrayOutStr.write(buf1);
byteArrayOutStr.close();
byteArrayOutStr.write(buf2);
byteArrayOutStr.close();
byteArrayOutStr.write(buf1);
System.out.println(
byteArrayOutStr.toString());
}
catch (Exception e) {
System.out.println(
"ByteArrayOutputStream is closed" );
}
}
}
|
References:
https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#close()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...