美文网首页
NIO:一份代码搞定NIO模式

NIO:一份代码搞定NIO模式

作者: 极客123 | 来源:发表于2018-11-21 18:55 被阅读0次
    package nio;
    
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.nio.Buffer;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    /***
     *    Java标准IO中,提供了基于流的IO实现: InputStream、OutputStream
     *    jdk1.4中,推出了基于块儿的IO实现: NIO(New I/O 的简称) :
     *          NIO两个核心组件: 缓冲Buffer 、 通道Channel
     *              缓冲: 读写数据的中转池
     *              通道: 缓冲数据的源头或者目的地
     *     java.nio.Buffer: 接口下的Buffer类族有原生类型对应的Buffer实现类
     *
     *     Nio中的Channel 是双向通道
     *
     *     读文件Demo简易流程:
     *           1、 将文件打开(文件流):  FileInputStream fileInputStream = new FileInputStream(new File("test.txt"));
     *           2、 取得文件的Channel :  FileChannel channel = fileInputStream.getChannel();
     *           3、 要从文件Channel中读数据就要使用Buffer: ByteBuffer buffer = ByteBuffer.allocate(1024);
     *               通过管道Channel将文件中的数据读到Buffer中:  channel.read(buffer);
     *           4、 搭建目的地文件管道
     *           5、 把buffer中的文件写出到目的地文件
     *           6、 关闭管道,注意关闭的顺序:读入--> 写出      关闭读入|关闭写出 ;
     */
    public class NioTestDemo {
    
        public static void main(String[] args) {
            try{
                //将文件打开为流模式
                FileInputStream fileInputStream = new FileInputStream(new File("D://a.txt"));
                //打开源文件流管道
                FileChannel readChannel = fileInputStream.getChannel();
                //定义缓冲区
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //对流出的地址文件打开流模式
                FileOutputStream fileOutputStream = new FileOutputStream(new File("E://a.txt"));
                //打开目的地文件流管道
                FileChannel writeChannel = fileOutputStream.getChannel();
    
                //开始读取
                while (true) {
                    //清除缓存区文件,保证缓冲区的干净
                    buffer.clear();
                    //源文件数据流入管道,到缓冲区
                    int len = readChannel.read(buffer);
                    if (len == -1 ) {
                        break;
                    }
                    //位置倒置:下一篇文章重点对BufferAPI介绍
                    buffer.flip();
                    //写入文件
                    writeChannel.write(buffer);
                }
                //关闭管道
                readChannel.close();
                writeChannel.close();
    
            }catch (Exception e){
    
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:NIO:一份代码搞定NIO模式

          本文链接:https://www.haomeiwen.com/subject/sixhqqtx.html