zoukankan      html  css  js  c++  java
  • NIO组件之channel

    Java NIO指的是new IO ,相对OIO,也称non-blocking IO,对应四种基本IO类型中的IO多路复用,主要有有三大核心组件,Channel(管道),Buffer(缓冲区),selector(选择器)

    channel相当于传统IO看的输入输出流合集,既可读也可写,有四类,

    FileChannel,文件通道,用于文件的数据读写

    SocketChannel套接字通道用于socket套接字TCP连接的数据读取,

    ServerSocketChannel,服务器套接字通道,允许监听TCP连接请求,为每个监听到的请求,创建一个SocketChannel套接安通道

    DatagramChanne数据报通道(UDP协议读取数据)

    1.fileChannel实践

    package com.example.demo;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    /**
     * Created by Administrator on 2019/9/22.
     */
    public class NioChannelTest {
        public static void main(String[] args) {
            fileChannelCopyFile();
        }
        public static void fileChannelCopyFile(){
            File srcFile=new File("srcFile.txt");
            File destFile=new File("destFile.txt");
    
            try{
                if(!destFile.exists()) destFile.createNewFile();
            }catch(Exception e){}
    
            FileInputStream fis=null;
            FileOutputStream fos=null;
            FileChannel inChannel=null;
            FileChannel outChannel=null;
            try{
                fis=new FileInputStream(srcFile);
                fos=new FileOutputStream(destFile);
            //通道的获取 inChannel
    =fis.getChannel(); outChannel=fos.getChannel(); int length=-1; ByteBuffer buf=ByteBuffer.allocate(1024); while((length=inChannel.read(buf))!=-1){ buf.flip(); int outlength=0; //将buf写入到输出通道 while((outlength=outChannel.write(buf))!=0){ System.out.println("the byte-len of being wrote"+outChannel); } //切换到写入模式,请空buf buf.clear(); } //强制刷新到磁盘 outChannel.force(true); }catch (Exception e){} finally{ try {//关闭通道 outChannel.close(); fos.close(); inChannel.close(); fis.close(); }catch (Exception e){} } } }

    输出:the byte-len of being wrote==29

    结果

  • 相关阅读:
    mysql优化
    c语言学习的第10天
    学习c语言的第9天
    学习c的第8天
    学习c的第7天
    学习c的第6天2
    c语言学习的第6天
    sed命令实战
    grep命令实战
    c语言学习的第五天
  • 原文地址:https://www.cnblogs.com/pu20065226/p/11569798.html
Copyright © 2011-2022 走看看