Java nio 的Channel接口继承了Closeable,为什么还要有close() 方法

时间:2023-01-28 14:51:24

首先Api是这样给出的:

Closeable的close()方法:

void close()
throws IOException
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
Specified by:

close in interface AutoCloseable
Throws:
IOException - if an I/O error occurs

Channel的close()方法:

void close()
throws IOException
Closes this channel.
After a channel is closed, any further attempt to invoke I/O operations upon it will cause a ClosedChannelException to be thrown.

If this channel is already closed then invoking this method has no effect.

This method may be invoked at any time. If some other thread has already invoked it, however, then another invocation will block until the first invocation is complete, after which it will return without effect.

Specified by:
close in interface AutoCloseable
Specified by:
close in interface Closeable
Throws:
IOException - If an I/O error occurs

很明显了,结论:子类通过继承然后重写父类方法对已有对象功能进行加强和优化,在nio中,以异常为例(其它的实现细节姑且不说),子类close()方法抛出的异常一定是父类close()方法抛出的异常的子类。

Java nio 的Channel接口继承了Closeable,为什么还要有close() 方法

那为什么Channel的close()方法不直接void close() throws ClosedChannelException呢?

因为这是多态的一种–向上转型,提高方法的可利用率!若是不懂向上转型的意义和用法,请到’Thinking In Java’ 查阅。

下面是演示demo:

package wen.xforce.beast.test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestNio {

public static void main(String[] args) {

try {
RandomAccessFile aFile = new RandomAccessFile("F://mess//test.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(64);
int bytesRead = inChannel.read(buf);
inChannel.close();
//关闭某个通道后,试图对其调用 I/O 操作就会导致 ClosedChannelException 被抛出。
//重写父类方法,定位的异常更加准确
int bytesRead2 = inChannel.read(buf);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Java nio 的Channel接口继承了Closeable,为什么还要有close() 方法