NIO
的通道类似于流,但有些区别如下:通道可以同时进行读写,而流只能读或者只能写;通道可以实现异步读写数据;通道可以从缓冲读数据,也可以写数据到缓冲。
BIO
中的 Stream
是单向的,例如 FileInputStream
对象只能进行读取数据的操作,而 NIO
中的通道(Channel
)是双向的,可以读操作,也可以写操作。
常用的 Channel
类有: FileChannel
、DatagramChannel
、ServerSocketChannel
和 SocketChannel
。【ServerSocketChannel
类似 ServerSocket
、SocketChannel
类似 Socket
】。其中FileChannel
用于文件的数据读写,DatagramChannel
用于 UDP
的数据读写,ServerSocketChannel
和 SocketChannel
用于 TCP
的数据读写。
FileChannel
主要用来对本地文件进行 IO
操作,常见的方法有:
public int read(ByteBuffer dst)
,从通道读取数据并放到缓冲区中public int write(ByteBuffer src)
,把缓冲区的数据写到通道中public long transferFrom(ReadableByteChannel src, long position, long count)
,从目标通道中复制数据到当前通道public long transferTo(long position, long count, WritableByteChannel target)
,把数据从当前通道复制给目标通道案例1:本地文件写数据
将hello,lwz
字符串写入到本地文件E:\\file01.txt
中:
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOTest1 {
public static void main(String[] args) throws IOException {
String str = "hello,lwz"; // 输出字符串
// 创建一个输出流 -> channel
FileOutputStream fileOutputStream = new FileOutputStream("E:\\file01.txt");
// 通过fileOutputStream获取对应的FileChannel
FileChannel channel = fileOutputStream.getChannel();
// 创建缓冲区,容量为1024字节
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);