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