NIO的通道类似于流,但有些区别如下:
- 通道可以同时进行读写而流只能读或者只能写
- 通道可以实现异步读写数据。
- 通道可以从缓种读数据,也可以写数据到缓冲:
- BIO中的stream是单向的,例如 FilelnputStream对象只能进行读取数据的操作,NIO中的通道(Channel)是双向的,可以读操作,也可以写操作。
- Channel在NIO中是一个接口public interface Channel extends Closeable0常用的 Channel类有:FileChanng2DatagramChannel、ServerSocketChannel 和SocketChannel。
- FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写,ServerSocketChannel和 SocketChannel用于TCP的数据读写。
主要用来对本地文件进行IO操作,常见的方法有
- 1) public int read(ByteBuffer dst从通道读取数据并放到缓净中
- 2) public int write(ByteBuffer src),把缓冲区的数据写到通道中
- 3) public long transferFrom(ReadableByteChannel src, long position, long count),目标通道中复制数据到当前通道
- 4) public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道
package com.zhuangxiaoyan.nio.channel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel {
public static void main(String[] args) throws IOException {
String str="hi 熊佳乐";
//创建一个输出流->channel
String filepath="D:\softwaresavfile\Github\JAVA_NIO\NIO\src\main\resources\test";
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
//通过FileOutputStream获取一个
// FileChannel的真实的类型是FileChannelimpl 类型
FileChannel fileChannel = fileOutputStream.getChannel();
//创建一个buffer
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
//数据放入到buffer
byteBuffer.put(str.getBytes());
//对bytebuffer 记性的flip
byteBuffer.flip();
//将bytebuffer的数据写入到filechannel
fileChannel.write(byteBuffer);
//关闭
fileOutputStream.close();
}
}



