xbgd 发表于 2013-1-15 01:30:53

java文件复制

java拷贝文件线程
package com.zhao_yi.sysutils.classes.copyfile;import java.io.*;import com.zhao_yi.sysutils.SysUtil;import com.zhao_yi.sysutils.classes.StringList;public class CopyFileThread extends Thread {private long CurCopied = 0;private boolean suspendRequested = false;private boolean terminateRequested = false;private StringList SrcFiles = new StringList();private StringList DstFiles = new StringList();private CopyFile copyfile = null;private String ErrMsg = "";public CopyFileThread(CopyFile copyfile) {    this.copyfile = copyfile;}public void AddCopyFiles(StringList SrcFiles, StringList DstFiles) {    this.SrcFiles.AddStrings(SrcFiles);    this.DstFiles.AddStrings(DstFiles);}private boolean CopyOneFile(String SrcFile, String DstFile) {    InputStream in = null;    OutputStream out = null;    try {      in = new FileInputStream(SrcFile);      out = new FileOutputStream(DstFile);      byte[] buf = new byte;      int len = 0;      while (!interrupted() && !terminateRequested) {      len = in.read(buf);      if (len == 0)          break;      out.write(buf, 0, len);      copyfile.OnCopyProcess(len);      }    } catch (IOException ex) {      ErrMsg = "拷贝文件的过程中 出现异常: " + ex.getMessage();    } finally {      try {      in.close();      out.close();      } catch (IOException ex) {      ErrMsg = "拷贝文件的过程中 出现异常: " + ex.getMessage();      }      return SysUtil.SameText("", ErrMsg);    }}public void run() {    try {      copyfile.OnCopyBegin();      int fileCount = SrcFiles.getCount();      for (int i = 0; i < fileCount; i++) {      CheckSuspended();      if (!interrupted() && !terminateRequested) {          String SrcFile = SrcFiles.Get(i);          String DstFile = DstFiles.Get(i);          if (!            (SysUtil.ForceDirectories(SysUtil.ExtractFilePath(DstFile)) &&               CopyOneFile(SrcFile, DstFile))            )            break;      }      }    } catch (Exception ex) {      ErrMsg = ex.getMessage();    } finally {      copyfile.OnCopyEnd(ErrMsg);    }}public synchronized void RequestSuspend() {    suspendRequested = false;}public synchronized void RequestResume() {    suspendRequested = false;    notify();}public synchronized void RequestTerminate() {    terminateRequested = true;    if (suspendRequested)      RequestResume();}public synchronized void CheckSuspended() {    while (suspendRequested && !interrupted()) {      try {      wait();      } catch (InterruptedException ex) {      ErrMsg = "暂停的过程中 被强行停止: " + ex.getMessage();      }    }}}

Java复制文件速度最快的算法
第一种方法,是采用普通的IO,Buffered流,速度一般;另一种是采用Channel流的transfer方法,速度超快。建议采用第二种方法。
public static long copyFile(File srcFile,File destDir,String newFileName){long copySizes = 0;if(!srcFile.exists()){   System.out.println("源文件不存在");   copySizes = -1;}else if(!destDir.exists()){   System.out.println("目标目录不存在");   copySizes = -1;}else if(newFileName == null){   System.out.println("文件名为null");   copySizes = -1;}else{   try {    BufferedInputStream bin = new BufferedInputStream(      new FileInputStream(srcFile));    BufferedOutputStream bout = new BufferedOutputStream(      new FileOutputStream(new File(destDir,newFileName)));    int b = 0 ,i = 0;    long t1 = System.currentTimeMillis();    while((b = bin.read()) != -1){   bout.write(b);   i++;    }    long t2 = System.currentTimeMillis();    bout.flush();    bin.close();    bout.close();    copySizes = i;    long t = t2-t1;    System.out.println("复制了" + i + "个字节\n" + "时间" + t);   } catch (FileNotFoundException e) {      e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   }}return copySizes; }public static long copyFile2(File srcFile,File destDir,String newFileName){long copySizes = 0;if(!srcFile.exists()){   System.out.println("源文件不存在");   copySizes = -1;}else if(!destDir.exists()){   System.out.println("目标目录不存在");   copySizes = -1;}else if(newFileName == null){   System.out.println("文件名为null");   copySizes = -1;}else{   try {    FileChannel fcin = new FileInputStream(srcFile).getChannel();    FileChannel fcout = new FileOutputStream(          new File(destDir,newFileName)).getChannel();    ByteBuffer buff = ByteBuffer.allocate(1024);    int b = 0 ,i = 0;//    long t1 = System.currentTimeMillis();      long size = fcin.size();    fcin.transferTo(0,fcin.size(),fcout);    //fcout.transferFrom(fcin,0,fcin.size());    //一定要分清哪个文件有数据,那个文件没有数据,数据只能从有数据的流向    //没有数据的文件//    long t2 = System.currentTimeMillis();    fcin.close();    fcout.close();    copySizes = size;//    long t = t2-t1;//    System.out.println("复制了" + i + "个字节\n" + "时间" + t);//    System.out.println("复制了" + size + "个字节\n" + "时间" + t);   } catch (FileNotFoundException e) {      e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   }}return copySizes; }

使用nio和io来测试一个100m的文件
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class CopyFile {    /**   * nio拷贝   * @param inFile源文件   * @param outFile 目标文件   * @return   * @throws Exception   */    public static long FileChannelCopy(String inFile,String outFile) throws Exception    {      long begin = System.currentTimeMillis();      File in = new File(inFile);            File out = new File(outFile);      FileInputStream fin = new FileInputStream(in);      FileOutputStream fout = new FileOutputStream(out);      FileChannel inc = fin.getChannel();      FileChannel outc = fout.getChannel();      int bufferLen = 2097152;      ByteBuffer bb = ByteBuffer.allocateDirect(bufferLen);      while (true)      {            int ret = inc.read(bb);            if (ret == -1)            {                      fin.close();                fout.flush();                fout.close();                break;            }            bb.flip();            outc.write(bb);            bb.clear();      }      long end = System.currentTimeMillis();      long runtime = 0;      if(end >begin)            runtime = end - begin;      return runtime;    }    /**   * io拷贝   * @param inFile 源文件   * @param outFile 目标文件   * @return   * @throws Exception   */    public static long FileStraeamCopy(String inFile,String outFile) throws Exception    {      long begin = System.currentTimeMillis();                File in = new File(inFile);      File out = new File(outFile);      FileInputStream fin=new FileInputStream(in);      FileOutputStream fout=new FileOutputStream(out);            int length=2097152;//2m内存      byte[] buffer=new byte;                while(true)      {            int ins=fin.read(buffer);            if(ins==-1)            {                fin.close();                fout.flush();                fout.close();                break;                            }else                fout.write(buffer,0,ins);                  }      long end = System.currentTimeMillis();      long runtime = 0;      if(end > begin)            runtime = end - begin;      return runtime;    }    static public void main(String args[]) throws Exception {      String inFile = "D:\\big4.pdf"; //源文件      String outFile = "D:\\big4copy1.pdf"; //输出文件1      String outFile2 = "D:\\big4copy2.pdf"; //输出文件2      long runtime1,runtime2;      runtime1 = FileChannelCopy(inFile,outFile);      runtime2 = FileStraeamCopy(inFile,outFile2);      System.out.println("FileChannelCopy running time:" + runtime1);      System.out.println("FileStraeamCopy running time:" + runtime2);    }}

一个简单的方式就是调用cmd命令,使用windows自带的功能来替你完成这个功能
我给你写个例子
import java.io.*;public class test{   public static void main(String[] args){      BufferedReader in = null;      try{         // 这里你就当作操作对dos一样好了 不过cmd /c 一定不要动         Process pro =Runtime.getRuntime().exec("cmd /c copy d:\\ReadMe.txt e:\\");         in = new BufferedReader(new InputStreamReader(pro.getInputStream()));         String str;         while((str = in.readLine()) != null){            System.out.println(str);         }      }catch(Exception e){            e.printStackTrace();      }finally{         if(in != null){               try{                   in.close();               }catch(IOException i){                  i.printStackTrace();               }         }      }   }}
页: [1]
查看完整版本: java文件复制