ByteArrayOutputSteam close() method in Java with Examples
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:
// Java program to illustrate // ByteArrayOutputStream close() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { try { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte [] buf = { 71 , 69 , 69 , 75 , 83 }; // close() is called byteArrayOutStr.close(); // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf); // Print the byteArrayOutputStream // as String System.out.println( byteArrayOutStr.toString()); } catch (Exception e) { System.out.println( "ByteArrayOutputStream is closed" ); } } } |
Beginner
Program 2:
// Java program to illustrate // ByteArrayOutputStream close() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { try { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte [] buf1 = { 71 , 69 , 69 , 75 , 83 }; byte [] buf2 = { 70 , 79 , 82 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf1); // close() is called byteArrayOutStr.close(); // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf2); // close() is called again byteArrayOutStr.close(); // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf1); // Print the byteArrayOutputStream // as String System.out.println( byteArrayOutStr.toString()); } catch (Exception e) { System.out.println( "ByteArrayOutputStream is closed" ); } } } |
w3wiki
References:
https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#close()