`

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[1024];
      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[length];
        
        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 楼 s21109 2012-04-28  
不错 很详细

相关推荐

    java文件复制功能

    java文件复制,使用java语言开发的,效果如windows 的复制和粘贴效果。

    java文件复制器

    一个简单的基于java实现的文件复制器,分享给大家学习

    java文件复制(全)

    可以复制单个文件或整个文件夹下的所有文件

    JAVA文件复制操作

    实现文本复制操作的简易JAVA代码,适用于JAVA初学者

    java文件复制,实现文件的复制

    利用java实现文件的复制整个文件夹内容,实现文件的复制

    JAVA文件复制

    这是JAVA SE中的文件复制的代码,很多人对于文件复制不是很理解,希望通过此代码可以帮助更多的人来理解怎么是用Java语言实现文件的复制

    java复制文件的4种方式

    java复制文件的4种方式 java复制文件的4种方式 java复制文件的4种方式

    java文件复制小程序

    用户输入原始文件地址。。。然后输入要复制到的目录。

    java文件复制器代码

    1)在FileCopy类中,建立copy方法,实现文件复制的内容; 2)程序中需要考虑输入输出异常处理; 3)在dos控制台窗口环境下,通过命令行参数运行程序,如:  Java FileCopy test1.txt test2.txt

    Java文件的复制源代码

    Java文件复制源代码(含使用Swing组件、无法复制文件夹)

    java 实现文件复制 源码

    实现简单的文件复制功能,适合java入门学习 输入输出部分

    Java多线程文件复制器

    Java实现多线的文件复制(界面)。 可以选择复制文件的路径,和复制到某处的路径。可以选择线程数量。

    java完美版文件复制器

    这是一个利用java swing做的一个文件复制器,你可以根据自己的需要选择复制的文件的类型,可以自己设定文件筛选的类型。反正是一款很实用的文件复制器。。相信我没错了。 注:解压密码仍然是:you'dbest

    java_文件复制(带有编码类型)

    BufferedWriter BufferedReader 具体例子

    File-Operation-by-java.rar_java 文件复制_operation

    本程序用java语言实现了文件流的几乎所有操作,如文件复制,移动,删除,新建等。

    文件复制(java代码实现)

    1)在FileCopy类中,建立copy方法,实现文件复制的内容; 2)程序中需要考虑输入输出异常处理; 3)在dos控制台窗口环境下,通过命令行参数运行程序。

    java文件复制(io流的转制)

    java编程,使用FileInputStream ,FileOutputStream 实现了把一个文件的内容复制到另外一个文件 /* * 多种类型文件的复制 */

    java 文件复制

    利用java io实现文件复制 public class FileCopy { public boolean copyFile (String srcPath, String desPath) throws FileNotFoundException{ File srcFile,desFile; srcFile=new File (srcPath); ...

Global site tag (gtag.js) - Google Analytics