1. 程式人生 > >Java nio 的Channel介面繼承了Closeable,為什麼還要有close() 方法

Java nio 的Channel介面繼承了Closeable,為什麼還要有close() 方法

首先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()方法丟擲的異常的子類。

這裡寫圖片描述

那為什麼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();
        }

    }

}

這裡寫圖片描述