ClosedChannelException in Java with Examples

16 Feb, 2022
The class ClosedChannelException is invoked when an I/O operation is attempted on a closed channel or a channel that is closed to the attempted operation. That is if this exception is thrown, however, does not imply the channel is completely closed but is closed to the attempted operation.
Syntax:
public class ClosedChannelException
extends IOException
The hierarchy of ClosedChannelException is as follows:
Now let us do see constructor details of this class before proceeding to it’s methods.
Now let us discuss the methods inherited from Throwable class. They are depicted in tabular format below ias follows:
Note: this refers to the object in whose context the method is being called.
Implementation: We are essentially going to create a channel, closing it, and then trying to perform a read operation on a closed channel. This will trigger the ClosedChannelException. The steps are as follows:
We will create an instance of RandomAccessFile class to open a text file from your system in “rw” i.e read-write mode.Now we create a channel to the opened file using FileChannel class.After that, we create a buffer to read bytes of data from this channel using ByteBuffer class.Further, Charset class, we define the encoding scheme as “US-ASCII”.Finally, before we start the process of reading this file, we close the channel.
We will create an instance of RandomAccessFile class to open a text file from your system in “rw” i.e read-write mode.
Now we create a channel to the opened file using FileChannel class.
After that, we create a buffer to read bytes of data from this channel using ByteBuffer class.
Further, Charset class, we define the encoding scheme as “US-ASCII”.
Finally, before we start the process of reading this file, we close the channel.
Therefore, when a read operation is attempted on this channel a ClosedChannelException is thrown. We catch the Exception in the catch block where you may add any Exception handling that is specific to your requirement, here we are only printing a message.
Example
Java
// Java Program to Illustrate Working of// ClosedChannelException // Importing required classes// Input output classesimport java.io.IOException;import java.io.RandomAccessFile;// Classes from java.nio packageimport java.nio.ByteBuffer;import java.nio.channels.ClosedChannelException;import java.nio.channels.FileChannel;import java.nio.charset.Charset; // Main class// For ClosedChannelExceptionpublic class GFG {     // Main driver method    public static void main(String args[])        throws IOException    {         // Try block to check for exceptions        try {             // Open a file in your system using the            // RandomAccessFile class Custom local directory            // on machine            RandomAccessFile randomAccessFile                = new RandomAccessFile(                    "D:/Documents/textDoc.txt", "rw");             // Now creating a channel using the FileChannel            // class to the file opened using the            // RandomAccessFile class            FileChannel fileChannel                = randomAccessFile.getChannel();             // Create a buffer to read bytes from the            // channel using the ByteBuffer class            ByteBuffer byteBuffer                = ByteBuffer.allocate(512);            Charset charset = Charset.forName("US-ASCII");             // Close the file channel            // We do this so the exception is thrown            fileChannel.close();             // Try to read from the fileChannel which is now            // closed            while (fileChannel.read(byteBuffer) > 0) {                 byteBuffer.rewind();                System.out.print(                    charset.decode(byteBuffer));                byteBuffer.flip();            }             // Closing the connections to free up memory            // resources using close() method            randomAccessFile.close();        }         // Catch block to handle the exceptions         // Handling Application specific Exception        catch (ClosedChannelException e) {             // Print message if exception is occurred            System.out.println(                "ClosedChannelException has occurred");        }    }}
Output:
simmytarika5
kk9826225
surindertarika1234
sumitgumber28
varshagumber28
Java-Exceptions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java