zoukankan      html  css  js  c++  java
  • Channel的使用

    Channel必须要通过buffer来读写

    1. Channel需要通过IO流的getChannel()方法获取

    2. buffer需要通过Channel的map()方法获取

    package com.io.channel;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.CharBuffer;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    
    public class ChannelB {
    
        public static void main(String[] args) {
    
    
            String path = "E:\fitnesse\workspace\javaio\resource\";
            String nameFilePath = path + "name.txt";
            String copyFilePath = path + "copy.txt";
            
            File nf = new File(nameFilePath);
            File cf = new File(copyFilePath);
            
    
            //第一步获取Channel,有很多种Channl,这里使用到的是FileChannel
            try(FileChannel inChannel = new FileInputStream(nf).getChannel();
                FileChannel outChannel = new FileOutputStream(cf).getChannel())
            {
                //从name.txt中读取内容到buffer中
                MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY , 0 , nf.length());
                
                //将从name.txt中读取的内容写入到copy.txt
                outChannel.write(buffer);
                buffer.clear();
                
                //设置编码和解码器
                Charset charset = Charset.forName("GBK");
                CharsetDecoder decoder = charset.newDecoder();        
                CharBuffer charBuffer =  decoder.decode(buffer);        
                System.out.println(charBuffer);
                
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
        }
    
    }

    name.txt文件内容

    执行程序后输出的内容

    1231542155112221
    45444545454454545
    41511111111111111111111111111111
    88888888888888888888888888888888888888

    copy.txt的内容

  • 相关阅读:
    .NET 异步详解
    spring batch简介
    Nginx 配置文件介绍
    局域网内组播
    qt自定义信号函数的那些坑
    传输文件到远程服务器
    vim复制指定行
    腾讯云获取公网ip
    ifconfig添加或删除ip
    程序中tar压缩文件
  • 原文地址:https://www.cnblogs.com/moonpool/p/5522479.html
Copyright © 2011-2022 走看看