Java实现文件拷贝的方法

java有两种文件流的

  • 字符流:Reader/Writer
  • 字节流:InputStream/OutputStream

如果文件不是普通的文本类型的话,就不能使用字符流了,所以通用的文件流还是字节流。这里使用字节流实现文件拷贝。

  1. 使用java.io.File中的方法
public static void copyByFileStreams(File source, File dest){
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try{
        inputStream = new FileInputStream(source);
        outputStream = new FileOutputStream(dest);
        //一次性读入内存,再一次性写入
        //byte[] b = new byte[(int)source.length()];
        //inputStream.read(b);
        //outputStream.write(b);
        //边读边写
        int len = 0;
        while((len = inputStream.read(b)) != -1){
            outputStream.write(len);
        }
    }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

}
  1. 使用java.nio.Channels中的方法
public static void copyByFileChannels(File source, File dest) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            inputStream = new FileInputStream(source);
            outputStream = new FileOutputStream(dest);

            FileChannel inputChannel = inputStream.getChannel();
            FileChannel outputChannel = outputStream.getChannel();

            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
  1. 使用Java7中Files.copy完成拷贝
 /**
     * 使用java7的Files.copy完成拷贝操作,其内部也是使用FileChannels
     * @param source
     * @param dest
     */
    public static void copyByJava7Files(File source, File dest) {
        try {
            Files.copy(source.toPath(),dest.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

平时最常用的应该就是第一种方式了,但是好像使用FileChannel效率更高,这个还没做性能比较,因为没来得及看源码,日后用到了再说吧。^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值