NIO在文件copy中的使用

package com.example.demo.controller.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 时间: 2018/5/10.
 *
 * @author zwf
 */
public class NioTest {
    public static void main(String[] args) throws IOException {
        String sourcePath = "D:\\报表\\111.txt";
        String path1 = "D:\\报表\\222.txt";

        nioBufferCopy(sourcePath,path1);
    }

    private static void nioBufferCopy(String sourcePath,String path) throws IOException {
        //文件1
        File file1 = new File(sourcePath);
        //文件2
        File file2 = new File(path);
        if (!file2.exists()){
            file2.createNewFile();
        }
        //文件输入流
        FileInputStream fis = new FileInputStream(file1);
        //文件输出流
        FileOutputStream fos = new FileOutputStream(file2);
        //获取文件输入流的通道
        FileChannel sourceCh = fis.getChannel();
        //获取文件输出流的通道,两个类型一样,说明通道可以是双向的
        FileChannel destCh = fos.getChannel();
        //通过输入流通道写给缓冲区数据,就是将通道中的数据 写入缓存块 buffer
        MappedByteBuffer mbb = sourceCh.map(FileChannel.MapMode.READ_ONLY,0,sourceCh.size());

//        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
//
//        byteBuffer.putChar('1');
//        //写转化为读
//        byteBuffer.flip();
//        destCh.write(byteBuffer);

        //通过输出流通道,获取缓冲区数据,就是将缓冲区中的数据 写入通道
        destCh.write(mbb);
        sourceCh.close();
        destCh.close();

    }



}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值