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

Netty——Channel的原理与实战

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

Netty——Channel的原理与实战

摘要

NIO的通道类似于流,但有些区别如下:

  • 通道可以同时进行读写而流只能读或者只能写
  • 通道可以实现异步读写数据。
  • 通道可以从缓种读数据,也可以写数据到缓冲:
  • BIO中的stream是单向的,例如 FilelnputStream对象只能进行读取数据的操作,NIO中的通道(Channel)是双向的,可以读操作,也可以写操作。
  • Channel在NIO中是一个接口public interface Channel extends Closeable0常用的 Channel类有:FileChanng2DatagramChannel、ServerSocketChannel 和SocketChannel。
  • FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写,ServerSocketChannel和 SocketChannel用于TCP的数据读写。

Channel的主要函数 FileChannel

主要用来对本地文件进行IO操作,常见的方法有

  • 1) public int read(ByteBuffer dst从通道读取数据并放到缓净中
  • 2) public int write(ByteBuffer src),把缓冲区的数据写到通道中
  • 3) public long transferFrom(ReadableByteChannel src, long position, long count),目标通道中复制数据到当前通道
  • 4) public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道
package com.zhuangxiaoyan.nio.channel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class NIOFileChannel {

    public static void main(String[] args) throws IOException {
        String str="hi 熊佳乐";
        //创建一个输出流->channel
        String filepath="D:\softwaresavfile\Github\JAVA_NIO\NIO\src\main\resources\test";
        FileOutputStream fileOutputStream = new FileOutputStream(filepath);
        //通过FileOutputStream获取一个
        // FileChannel的真实的类型是FileChannelimpl 类型
        FileChannel fileChannel = fileOutputStream.getChannel();
        //创建一个buffer
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        //数据放入到buffer
        byteBuffer.put(str.getBytes());
        //对bytebuffer 记性的flip
        byteBuffer.flip();
        //将bytebuffer的数据写入到filechannel
        fileChannel.write(byteBuffer);
        //关闭
        fileOutputStream.close();
    }
}

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

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

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