复制文件(夹)

来源:互联网 发布:英语翻译软件那个好 编辑:程序博客网 时间:2024/04/28 22:29
文件复制:
原始方法(实际上也是用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 );

          }

       }



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











0 0