Java NIO的通道类似流,但又有些不同:
- 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
- 通道可以异步地读写。
- 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:

Channel的实现
这些是Java NIO中最重要的通道的实现:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel 从文件中读写数据。
DatagramChannel 能通过UDP读写网络中的数据。
SocketChannel 能通过TCP读写网络中的数据。
ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
public static void demo4(){
// 文件--> 管道--> buffer
try {
ByteBuffer buf = ByteBuffer.allocate(1024);
RandomAccessFile aFile = new RandomAccessFile("D://1.txt", "rw");
FileChannel inChannel = aFile.getChannel();
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();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void demo3(){
//通过Channel 写数据
//数据 -> 数组 -> buffer -> channel -> 文件
try {
RandomAccessFile accessFile= new RandomAccessFile("D://1.txt","rw");
FileChannel channel = accessFile.getChannel();
byte[] bytes = new String("abcd").getBytes();
ByteBuffer byteBuffer= ByteBuffer.wrap(bytes);
channel.write(byteBuffer);
byteBuffer.clear();
byteBuffer.put(new String("efg").getBytes());
byteBuffer.flip();// buffer 由写模式转为读模式
channel.write(byteBuffer);
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
本文深入探讨Java NIO的通道(Channel)概念,解释其与流(Stream)的区别,如双向读写能力、异步操作及数据必须通过缓冲区(Buffer)处理的特点。并详细介绍了FileChannel、DatagramChannel、SocketChannel和ServerSocketChannel等关键实现,通过示例代码展示如何使用Channel进行文件读写。
319

被折叠的 条评论
为什么被折叠?



