Java NIO 的通道相似流,但又有些不一樣:java
正如上面所說,從通道讀取數據到緩衝區,從緩衝區寫入數據到通道。以下圖所示:編程
這些是 Java NIO 中最重要的通道的實現:服務器
java.nio.channels.Channel 接口: |--FileChannel |--SocketChannel |--ServerSocketChannel |--DatagramChannel
Java 針對支持通道的類提供了 getChannel() 方法。網絡
本地IO FileInputStream/FileOutputStream/RandomAccessFile併發
網絡IO Socket/ServerSocket/DatagramSocketdom
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();
在 JDK 1.7 中的 NIO.2 針對各個通道提供了靜態方法 open()異步
FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ)
StandardOpenOption爲一個enum類型,常見的文件操做方式有如下幾種:工具
public enum StandardOpenOption implements OpenOption { READ, // 讀 WRITE, // 寫 APPEND, // 追加 CREATE, // 沒有新建,有就覆蓋 CREATE_NEW, // 沒有就新建,有就報錯 }
在 JDK 1.7 中的 NIO.2 的 Files 工具類的 newByteChannel()code
SeekableByteChannel channel = Files.newByteChannel(Paths.get("1.png"), StandardOpenOption.READ);
下面是一個使用FileChannel讀取數據到Buffer中的示例:blog
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
注意 buf.flip() 的調用,首先讀取數據到 Buffer,而後反轉 Buffer,接着再從 Buffer 中讀取數據。下一節會深刻講解 Buffer 的更多細節。
轉載自併發編程網 – ifeve.com,本文連接地址: Java NIO系列教程(二) Channel