一、基本介绍
1、NIO的通道类似于流,但有些区别
 (1)通道可以同时进行读写,而流只能读或者只能写
 (2)通道可以实现异步读写数据
 (3)通道可以从缓冲读数据,也可以写数据到缓冲
2、BIO中的stream是单向的,例如FileInputStream对象只能进行读取数据的操作,而NIO中的通道(Channel)是双向的,可以读操作,也可以写操作。
3、Channel在NIO中是一个接口
 public interface Channel extends Closeable
4、常用的Channel类有:FileChannel、DatagramChannel、ServerSocketChannel(类似ServerSocket)、SocketChannel(类似Socket)。
 真实类型:
5、FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写,ServerSocketChannel和SocketChannel用于TCP的数据读写。
二、FileChannel类
1、FileChannel类主要用来对本地文件进行IO操作,常见方法有
 读和写是站在channel通道的角度
 (1)public abstract int read(ByteBuffer dst):从通道读取数据并放到缓冲区中
 (2)public abstract int write(ByteBuffer src):把缓冲区的数据写到通道中
 (3)public abstract long transferFrom(ReadableByteChannel src, long position, long count):从目标通道中复制数据到当前通道
 (4)public abstract long transferTo(long position, long count, WritableByteChannel target):把数据从当前通道复制给目标通道
三、案例1:本地文件写数据
1、使用ByteBuffer(缓冲)和FileChannel(通道),将“hell,你好”写入到file01.txt中
 2、文件不存在就创建
 3、代码
NIOFileChannel01.java
package netty.channel;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel01 {
	public static void main(String[] args) throws Exception {
		String str = "hello,你好";
		//创建一个输出流->包装到channel中
		FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");
		
		//通过fileOutputStream输出流获取对应的FileChannel
		//这个fileChannel真实类型是FileChannelImpl
		FileChannel fileChannel = fileOutputStream.getChannel();
		
		//创建一个缓冲区ByteBuffer
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		
		//将str放入到byteBuffer中
		byteBuffer.put(str.getBytes());
		
		//对byteBuffer进行flip
		byteBuffer.flip();
		
		//将byteBuffer里的数据,写入到fileChannel
		fileChannel.write(byteBuffer);
		
		//关闭流
		fileOutputStream.close();
	}
}读写翻转前:
翻转后:
四、案例2:本地文件读数据
1、使用ByteBuffer(缓冲)和FileChannel(通道),将file01.txt中的数据读入到程序,并显示在控制台屏幕
 2、假定文件已经存在
 3、代码
NIOFileChannel02.java
package netty.channel;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel02 {
	public static void main(String[] args) throws Exception {
		//创建文件的输入流
		File file = new File("d:\\file01.txt");
		FileInputStream fileInputStream = new FileInputStream(file);
		
		//通过fileInputStream获取对应的FileChannel -> 实际类型FileChannelImpl
		FileChannel fileChannel = fileInputStream.getChannel();
		
		//创建缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		
		//将通道的数据读入到byteBuffer中
		fileChannel.read(byteBuffer);
		
		//将byteBuffer的字节数据转成String
		System.out.println(new String(byteBuffer.array())); //返回buffer中的字节数组hb
		
		//关闭流
		fileInputStream.close();
	}
}













![[附源码]Python计算机毕业设计大学生志愿者管理系统](https://img-blog.csdnimg.cn/d060c19b9eba49e3980bd671ac6742b5.png)




