IO廣義兩大類:File IO、Stream IO 《==》通道兩大類:FileChannel(文件通道)、SocketChannel-ServerSocketChannel-DatagramChannel(套接字通道)。
通道的單向和雙向:實現ReadableByteChannel read()方法《==》實現WritableByteChannel write()方法。
1 /**
2 * 基於基本channel buffer的文件復制操作
3 */
4 public static void fileTransferByNormal() {
5 try {
6 RandomAccessFile afile = new RandomAccessFile("hello.txt", "rw");
7 RandomAccessFile bfile = new RandomAccessFile("hehe.txt", "rw");
8 FileChannel ac = afile.getChannel();
9 FileChannel bc = bfile.getChannel();
10
11 ByteBuffer bf = ByteBuffer.allocateDirect(16 * 1024);
12 while (ac.read(bf) != -1) {
13 bf.flip();
14 while (bf.hasRemaining()) {
15 bc.write(bf);
16 }
17 bf.clear();
18 }
19 } catch (FileNotFoundException e) {
20 e.printStackTrace();
21 } catch (IOException e) {
22 e.printStackTrace();
23 }
24 }
Blocking Nonblocking:非阻塞模式不會讓調用的線程休眠,要麼請求立即完成,或者返回誤操作。Stream-oriented可以設置nonblocking。 Socket Channel 繼承自SelectableChannel=》Selectors=》多路復用。(非阻塞IO)。 通道關閉: 通道不能被重復利用,打開的通道代表與一個特定IO服務的特定鏈接並封裝該鏈接的狀態,通道關閉則鏈接丟失。 通道上的多次close(),無影響。 如果一個線程在一個通道上被阻塞同時被中斷,則該通道將被關閉,線程拋出ClosedByInterruptException異常。 一個線程的interrupt status被設置,且該線程視圖訪問一個通道,那麼這個通道會被關閉,並拋出ClosedByInterruptException異常。 通道上休眠線程的中斷區別於selectors上的休眠線程的中斷。 實現InterruptableChannel的Channel可以在任何時候被關閉,同時通道上的休眠線程會被喚醒並接收到一個AsynchronousInterruptedException。異步關閉。