Nio学习之通过通道实现最简单的文件复制代码

通过通道来实现文件的复制,输入参数分别为sourceFile和destFile,表示要复制的文件,和复制完成后目标文件的名称

通过参数的形式输入,如果文件不可读或者不可写则抛出异常

package part18;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by xueqin on 17/5/30.
 */
public class ChannelCopy {
    private static final int BSIZE=1024;

    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("arguments:sourceFile destFile");
            System.exit(1);
        }
        FileChannel in = new FileInputStream(args[0]).getChannel(),
                out = new FileOutputStream(args[1]).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        while (in.read(buffer) != -1) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
        }


    }
}
解释:
首先通过判断参数长度是否为2来获取sourceFile,destFile的路径和名称
然后通过FileInputStream和FileOutoutStream,ByteBuffer来完成文件的循环复制。通过while循环来判断原文件是否还有未被复制的,直到全部被
复制,才结束。
 
当然通过通道的特殊方法transferTo()和transferFrom()方法允许我们直接把通道和通道相连
于是升级版的复制文件方法如下:
 
package part18;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * Created by xueqin on 17/5/30.
 */
public class TransferTo {
    public static void main(String[] args) throws Exception{
        if (args.length != 2) {
            System.out.println("arguments:sourceFile destFile"
            );
            System.exit(1);
        }
        FileChannel in = new FileInputStream(args[0]).getChannel(),
                out = new FileOutputStream(args[1]).getChannel();
        in.transferTo(0, in.size(), out);
        out.transferFrom(in, 0, in.size());

    }
}
其中:in.transferTo和out.transferFrom都可以完成复制,两者实现的效果是相同的。
除去参数判断。如果只写方法,则只有三行代码如下
public static void copyFile(String sourceFile,String destFile) throws Exception {
    FileChannel in = new FileInputStream(sourceFile).getChannel(),
            out = new FileOutputStream(destFile).getChannel();
    in.transferTo(0, in.size(), out);
    //out.transferFrom(in, 0, in.size());
}
完工,可以看到很简单,以后再也不用担心写出文件复制代码而担心了。你需要的仅仅是两个参数,两个通道,一个transfer方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值