简介:
基本上,所有的IO在NIO中都从一个Channel开始。Channel有点像流,数据可以从Channel读到Buffer中,也可以从Buffer写到Channel中。
Channel类虽然像流,但是和流有很大的区别,主要有以下两点:
- Channel只能操作Buffer中的数据,程序也不能直接访问Channel中的数据,只能通过Buffer。
- Channel可以将硬盘中的文件直接映射为Buffer。
JAVA中一些主要的Channel的实现
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel的基本使用
Java NIO中的FileChannel是一个连接到文件的通道。可以通过该通道读写文件。
FileChannel无法设置为阻塞模式,因为它总是运行在阻塞模式下。
- 创建FileChannel
在使用FileChannel之前,必须先创建它。创建方式有两种
第一种:使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。
//1 创建RandomAccessFile
RandomAccessFile raf = new RandomAccessFile("D:\\FileText\\Hello.txt","r");
//2 获取通道
FileChannel channel = raf.getChannel();
第二种:在JDK1.7之后才能使用,FileChannel.open()方法。
FileChannel channel = FileChannel.open(Paths.get("D:\\FileText\\Hello.txt"), StandardOpenOption.READ);
- 从FileChannel读取数据
调用read()方法可以读取FileChannel中的数据。
首先,分配一个Buffer,将FileChannel中读取中的数据将被读到Buffer中。
然后,调用FileChannel.read()方法。该方法将数据从FileChannel读取到Buffer中。read()方法返回的int值表示有该数据大小的字节读取到了Buffer中,如果返回值是-1,表示到了文件末尾。
//读取
ByteBuffer buf = ByteBuffer.allocate(1024);
while (channel.read(buf)>0){
//切换为读取模式
buf.flip();
String data = new String(buf.array(),0,buf.limit());
System.out.println(data);
buf.clear();
}
- 向FileChannel中写数据
使用FileChannel.write()方法向FileChannel写数据,该方法的参数是一个Buffer。
注意因为无法保证write()方法一次能向FileChannel写完所有字节,因此需要重复调用write()方法,直到Buffer中已经没有尚未写入通道的字节。所以推荐在while循环中调用写方法。
public class ChannelWrite {
public static void main(String[] args) throws Exception {
FileChannel fileChannel = FileChannel.open(Paths.get("out.txt"), StandardOpenOption.WRITE);
String data = "大哥大嫂过年好~";
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(data.getBytes());
buf.flip();
fileChannel.write(buf);
buf.clear();
fileChannel.close();
}
}
4.关闭FileChannel
用完FileChannel后需调用close()方法将其关闭。