Java的ClosedChannelException 示例
当在关闭的通道或对尝试的操作关闭的通道上尝试 I/O 操作时,会调用类 ClosedChannelException。也就是说,如果抛出此异常,并不意味着通道已完全关闭,而是已对尝试的操作关闭。
句法:
public class ClosedChannelException
extends IOException
ClosedChannelException 的层次结构如下:
现在让我们在继续研究它的方法之前先看看这个类的构造函数细节。
Constructor | Description |
---|---|
ClosedChannelException() | Constructs an instance of the class |
现在让我们讨论从 Throwable 类继承的方法。它们以下面的表格格式描述如下:Method Description addSuppressed(Throwable exception) Add this exception to the exceptions that were suppressed so that this exception could be dispatched. fillInStackTrace() Records within this Throwable object information about the current state of the stack frame for the current thread and fills in the execution stack trace. getCause() Returns the cause of this Throwable or null if the cause is unknown. getLocalizedMessage() Returns a localized description of this Throwable. Subclasses may override the description. If the subclass doesn’t override this method then the result will be the same as that of getMessage(). getMessage() Return the detailed message description of this Throwable. getStackTrace() Returns an array of stack trace elements, each representing one stack frame. Gives access to the stack trace information printed by printStackTrace(). getSuppressed() Returns an array containing all the exceptions that were suppressed in order to dispatch this exception. initCause(Throwable cause) Initializes the cause of this Throwable with the given value. printStackTrace() Prints this Throwable and its backtrace on the error output stream. printStackTrace(PrintStream s) Prints this Throwable and its backtrace on the specified PrintStream. printStackTrace(PrintWriter s) Prints this Throwable and its backtrace to the specified PrintWriter. setStackTrace(StackTraceElement[] stackTrace) Sets the stack trace elements of this Throwable. It is designed for Remote Procedure Call Frameworks and advanced systems, it allows the client to override the default stack trace. toString() Returns a short description of this Throwable in the format, Name of the class of this object: Result of invoking the object’s getLocalizedMessage(). If getLocalizedMessage() returns null, then only the class name is returned.
Note: this refers to the object in whose context the method is being called.
实现:我们本质上将创建一个通道,关闭它,然后尝试在关闭的通道上执行读取操作。这将触发 ClosedChannelException。步骤如下:
- 我们将创建一个 RandomAccessFile 类的实例,以“rw”即读写模式从您的系统打开一个文本文件。
- 现在我们使用 FileChannel 类为打开的文件创建一个通道。
- 之后,我们创建一个缓冲区来使用 ByteBuffer 类从该通道读取数据字节。
- 此外,Charset 类,我们将编码方案定义为“US-ASCII”。
- 最后,在我们开始读取这个文件的过程之前,我们关闭通道。
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.
例子
Java
// Java Program to Illustraye Working of
// ClosedChannelException
// Importing required classes
// Input output classes
import java.io.IOException;
import java.io.RandomAccessFile;
// Classes frorm java.nio package
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
// Main class
// For ClosedChannelException
public 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 occured
System.out.println(
"ClosedChannelException has occurred");
}
}
}
输出: