JAVA Nio编程 Channel

通道介绍

其实通道和流还是有点相似的,但是又不完全像。
1、流只能读或者写,通道可以同时实现读写。
2、通道可以实现异步读写。
3、通道可以写缓冲区,也可以读缓冲区。
4、他们都有很多特定的子类(这个叫做工厂模式的应用)
5、在这里插入图片描述

实战

将“java yyds”写到我们的java.txt文件里面

	public static void main(String[] args) throws Exception{
		String str = "java yyds";
		FileOutputStream fos = new FileOutputStream("E:\\java.txt");
		FileChannel channel = fos.getChannel();
		// 创建缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		// 放进去
		byteBuffer.put(str.getBytes());
		// 反转位置
		byteBuffer.flip();
		channel.write(byteBuffer);
		fos.close();
	}

ok了,家人们。

既然写了,那就再读一下。

FileInputStream fis = new FileInputStream("E:\\java.txt");
		FileChannel channel = fis.getChannel();
		// 创建缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		channel.read(byteBuffer);
		System.out.println(new String(byteBuffer.array()));
		fis.close();

梅开二度,我现在读到了java.txt,我把它写到我们的java1.txt中。

public static void main(String[] args) throws Exception{
		FileInputStream fis = new FileInputStream("E:\\java.txt");
		FileOutputStream fos = new FileOutputStream("E:\\java1.txt");
		FileChannel channel = fis.getChannel();
		FileChannel channel1 = fos.getChannel();
		// 创建缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		// 读入缓冲区
		while (true){
			// 下一次清空
			byteBuffer.clear();
			int read = channel.read(byteBuffer);
			if(read == -1){
				break;
			}
			// 反转写进去
			byteBuffer.flip();
			channel1.write(byteBuffer);
		}
		fis.close();
		fos.close();
		
	}

我先用缓冲区读取,再写进去。
在这里插入图片描述

还可以拷贝文件,我现在拷贝一个java.txt

	public static void main(String[] args) throws Exception{
		FileInputStream fis = new FileInputStream("E:\\java.txt");
		FileOutputStream fos = new FileOutputStream("E:\\java2.txt");
		FileChannel channel = fis.getChannel();
		FileChannel channel1 = fos.getChannel();
		channel1.transferFrom(channel,0,channel.size());
		fis.close();
		fos.close();
		
	}

其实读写还可以通过多Buffer完成

public static void main(String[] args) throws Exception {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		InetSocketAddress inetSocketAddress = new InetSocketAddress(9999);
		// 将端口绑定socket
		serverSocketChannel.socket().bind(inetSocketAddress);
		// 创建Buffer数组
		ByteBuffer[] buffers = new ByteBuffer[3];
		buffers[0] = ByteBuffer.allocate(10);
		buffers[1] = ByteBuffer.allocate(10);
		buffers[2] = ByteBuffer.allocate(10);
		// 等待连接
		SocketChannel socketChannel = serverSocketChannel.accept();
		// 读取
		long read = socketChannel.read(buffers);
		// 反转
		Arrays.asList(buffers).forEach(buffer -> buffer.flip());
		socketChannel.write(buffers);
	}

其实我们还可以指定读多少,写多少。但是没什么意义,就不搞了。

结束语

再见再见再见再见再见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值