java 复制文件

来源:互联网 发布:淘宝情侣装专卖店 编辑:程序博客网 时间:2024/06/05 10:55

package sss;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class C1 {
 /**
  * 用文件通道的方式来进行文件复制
  *
  * @param s
  * @param t
  */
 public void fileChannelCopy(File s, File t) {
  FileInputStream fi = null;

  FileOutputStream fo = null;

  FileChannel in = null;

  FileChannel out = null;
  try {
   fi = new FileInputStream(s);

   fo = new FileOutputStream(t);

   in = fi.getChannel();// 得到对应的文件通道

   out = fo.getChannel();// 得到对应的文件通道

   in.transferTo(0, in.size(), out);// 连接两个通道,并且从in通道读取,然后写入out通道
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    fi.close();

    in.close();

    fo.close();

    out.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

 }

 /**
  * 流复制
  *
  * @param s
  * @param t
  */
 public void copy(File s, File t) {
  InputStream fis = null;
  OutputStream fos = null;

  try {
   fis = new BufferedInputStream(new FileInputStream(s));
   fos = new BufferedOutputStream(new FileOutputStream(t));
   byte[] buf = new byte[2048];
   int i;
   while ((i = fis.read(buf)) != -1) {
    fos.write(buf, 0, i);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    fis.close();
    fos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  File s = new File("D:\\ORACLE执行计划和SQL调优教程.rar");
  File t = new File("E:\\work\\111.rar");

  File t1 = new File("E:\\work\\222.rar");

  long start, end;
  C1 c = new C1();
  start = System.currentTimeMillis();
  c.fileChannelCopy(s, t);
  end = System.currentTimeMillis();
  System.out.println("FileChannel复制,用时" + (end - start) + "ms");

  start = System.currentTimeMillis();
  c.copy(s, t1);
  end = System.currentTimeMillis();

  System.out.println("buffered复制,用时" + (end - start) + "ms");

 }

}

0 0