栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA Nio编程 Channel

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
	}

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

结束语

再见再见再见再见再见

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970702.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号