复制文件(夹)

文件复制:
原始方法(实际上也是用nio来操作的):
1、一次性读取

      FileInputStream fis = new FileInputStream("D:\\test.jpg");

      FileOutputStream fos = new FileOutputStream("D:\\test1.jpg");

      int n = fis.available();

      byte[]file = new byte[n];

      fis.read(file);

      fos.write(file);

      fis.close();

      fos.close();

2、按字节读取

      FileInputStream fis = new FileInputStream("D:\\test.jpg");

      FileOutputStream fos = new FileOutputStream("D:\\test1.jpg");

      int c;

      while((c=fis.read())!=-1){

         fos.write(c);

      }

      fis.close();

      fos.close();

3、按固定大小读取

         FileInputStream fis = new FileInputStream("D:\\test.jpg");

         FileOutputStream fos = new FileOutputStream("D:\\test1.jpg");

         byte []b = new byte[128];

         int len;

         while((len=fis.read(b))!=-1){

            fos.write(b,0,len);

         }

         fis.close();

         fos.close();

利用NIO:
一次性复制

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.channels.FileChannel;

publicclass test1{

   publicvoid fileCopy(String inFileName,String outFileName) throws IOException{

      File in = new File(inFileName);

      File out = new File(outFileName);

      //路径不存在时创建路径

        if(out.getParentFile()!=null){

          out.getParentFile().mkdirs();

        }

       FileChannel inChannel = new FileInputStream( in ).getChannel();

       FileChannel outChannel = new FileOutputStream( out ).getChannel();

       try{

          //一次性全部复制

           inChannel.transferTo(0, inChannel.size(), outChannel);

       }

       catch (IOException e) {

         throw e;

      }

       finally{

          if ( inChannel != null ){

             inChannel.close();

          }

          if ( outChannel != null ){

             outChannel.close();

          }

       }

   }

   publicstaticvoid main(String[]args) throws IOException{

      test1 test = new test1();

      //路径"E:\\IMImg\\2014\\10\\"要存在否则需要手动创建

      test.fileCopy("E:\\IMImg\\2014\\9\\1414564179449xxx.jpg""E:\\IMImg\\2014\\12\\111\\112\\113\\114\\aa.jpg");

   }

}

固定大小复制
其它代码一样,try里面的代码改为:

       try{

          //最好不要太小

          int maxCount = 1024;

          long size = inChannel.size();

          long position = 0;

          while ( position < size )

          {

          position += inChannel.transferTo( position, maxCount, outChannel );

          }

       }



文件夹复制:
利用复制文件的方法,不断把文件夹下的文件一个个复制过去











版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/u/1987489/blog/491326

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值