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的内容

原文地址:https://www.cnblogs.com/moonpool/p/5522479.html