一直困扰着我,用Java复制文件的唯一方法是打开流,声明缓冲区,读入一个文件,循环遍历并将其写出到另一流。Web上散布着这种解决方案的类似但仍然略有不同的实现。
有没有一种更好的方法可以保留在Java语言的范围内(意味着不涉及执行OS特定的命令)?也许在某个可靠的开源实用程序包中,这至少会掩盖该基本实现并提供一线解决方案?
一直困扰着我,用Java复制文件的唯一方法是打开流,声明缓冲区,读入一个文件,循环遍历并将其写出到另一流。Web上散布着这种解决方案的类似但仍然略有不同的实现。
有没有一种更好的方法可以保留在Java语言的范围内(意味着不涉及执行OS特定的命令)?也许在某个可靠的开源实用程序包中,这至少会掩盖该基本实现并提供一线解决方案?
Answers:
如上面的工具包所述,Apache Commons IO尤其是FileUtils是必经之路。copyFile() ; 它为您处理所有繁重的工作。
并且作为一个后记,请注意,FileUtils的最新版本(例如2.0.1发行版)增加了使用NIO复制文件的功能。NIO可以大大提高文件复制性能,这在很大程度上是因为NIO例程将复制直接推迟到OS /文件系统,而不是通过在Java层中读写字节来处理。因此,如果您正在寻找性能,那么可能值得检查一下您是否在使用最新版本的FileUtils。
我会避免使用像Apache Commons这样的大型api。这是一个简单的操作,它内置在新NIO包中的JDK中。以前的答案中已经链接了这种方法,但是NIO api中的关键方法是新功能“ transferTo”和“ transferFrom”。
链接的文章之一展示了一种很好的方法,可以使用transferFrom将功能集成到代码中:
public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}学习NIO可能会有些棘手,因此您可能只想在开始尝试通宵学习NIO之前就信任此机制。从个人经验来看,如果您没有经验,并且是通过java.io流介绍给IO的,则可能很难学习。
现在,在Java 7中,您可以使用以下try-with-resource语法:
public static void copyFile( File from, File to ) throws IOException {
    if ( !to.exists() ) { to.createNewFile(); }
    try (
        FileChannel in = new FileInputStream( from ).getChannel();
        FileChannel out = new FileOutputStream( to ).getChannel() ) {
        out.transferFrom( in, 0, in.size() );
    }
}或者,更好的是,这也可以使用Java 7中引入的新Files类来实现:
public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
}很时髦,是吗?
package com.yourcompany.nio;
class Files {
    static int copyRecursive(Path source, Path target, boolean prompt, CopyOptions options...) {
        CopyVisitor copyVisitor = new CopyVisitor(source, target, options).copy();
        EnumSet<FileVisitOption> fileVisitOpts;
        if (Arrays.toList(options).contains(java.nio.file.LinkOption.NOFOLLOW_LINKS) {
            fileVisitOpts = EnumSet.noneOf(FileVisitOption.class) 
        } else {
            fileVisitOpts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        }
        Files.walkFileTree(source[i], fileVisitOpts, Integer.MAX_VALUE, copyVisitor);
    }
    private class CopyVisitor implements FileVisitor<Path>  {
        final Path source;
        final Path target;
        final CopyOptions[] options;
        CopyVisitor(Path source, Path target, CopyOptions options...) {
             this.source = source;  this.target = target;  this.options = options;
        };
        @Override
        FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        // before visiting entries in a directory we copy the directory
        // (okay if directory already exists).
        Path newdir = target.resolve(source.relativize(dir));
        try {
            Files.copy(dir, newdir, options);
        } catch (FileAlreadyExistsException x) {
            // ignore
        } catch (IOException x) {
            System.err.format("Unable to create: %s: %s%n", newdir, x);
            return SKIP_SUBTREE;
        }
        return CONTINUE;
    }
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        Path newfile= target.resolve(source.relativize(file));
        try {
            Files.copy(file, newfile, options);
        } catch (IOException x) {
            System.err.format("Unable to copy: %s: %s%n", source, x);
        }
        return CONTINUE;
    }
    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        // fix up modification time of directory when done
        if (exc == null && Arrays.toList(options).contains(COPY_ATTRIBUTES)) {
            Path newdir = target.resolve(source.relativize(dir));
            try {
                FileTime time = Files.getLastModifiedTime(dir);
                Files.setLastModifiedTime(newdir, time);
            } catch (IOException x) {
                System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
            }
        }
        return CONTINUE;
    }
    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            System.err.println("cycle detected: " + file);
        } else {
            System.err.format("Unable to copy: %s: %s%n", file, exc);
        }
        return CONTINUE;
    }
}long bytes = java.nio.file.Files.copy( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES,
                 java.nio.file.LinkOption.NOFOLLOW_LINKS);long bytes = java.nio.file.Files.move( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.ATOMIC_MOVE,
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING);long bytes = com.yourcompany.nio.Files.copyRecursive( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
                 java.nio.file.LinkOption.NOFOLLOW_LINKS );在Java 7中很容易...
File src = new File("original.txt");
File target = new File("copy.txt");
Files.copy(src.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);要复制文件并将其保存到目标路径,可以使用以下方法。
public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}请注意,所有这些机制仅复制文件的内容,而不复制诸如权限之类的元数据。因此,如果您要在Linux上复制或移动可执行文件.sh文件,则新文件将不可执行。
为了真正复制或移动文件,即获得与从命令行复制相同的结果,您实际上需要使用本机工具。Shell脚本或JNI。
显然,这可以在Java 7- http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html中修复。手指交叉!
Google的Guava库也有一个复制方法:
公共静态无效副本(文件 从, 文件 到) 引发IOException
警告:如果to代表现有文件,则该文件将被的内容覆盖from。如果to并且
  from引用相同的文件,则该文件的内容将被删除。
参数:from -源文件to-目标文件
抛出:
IOException -如果发生I / O错误
 IllegalArgumentException-如果from.equals(to)
在Java 7中作为标准功能提供,path.copyTo:http : //openjdk.java.net/projects/nio/javadoc/java/nio/file/Path.html http://java.sun.com/docs/books/ tutorial / essential / io / copy.html
我不敢相信他们花了这么长时间来标准化文件复制这样的常见和简单的方法:(
上面的代码三个可能的问题:
这就是为什么org.apache.tools.ant.util.ResourceUtils.copyResource如此复杂。还要注意,尽管transferFrom正常,但transferTo在Linux上的JDK 1.4上中断(请参见Bug ID:5056395)– Jesse Glick Jan
如果您已经在使用Spring的Web应用程序中,并且不想将Apache Commons IO包含在其中以进行简单的文件复制,则可以使用Spring框架的FileCopyUtils。
您可以通过以下三种方式轻松地用单行代码复制文件!
Java7:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}Appache Commons IO:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}番石榴:
private static void copyFileUsingGuava(File source,File dest) throws IOException{
    Files.copy(source,dest);          
}Files.copy仅使用2个参数Path即可Stream。只需添加参数StandardCopyOption.COPY_ATTRIBUTES或StandardCopyOption.REPLACE_EXISTING为Path到Path
                    public static void copyFile(File src, File dst) throws IOException
{
    long p = 0, dp, size;
    FileChannel in = null, out = null;
    try
    {
        if (!dst.exists()) dst.createNewFile();
        in = new FileInputStream(src).getChannel();
        out = new FileOutputStream(dst).getChannel();
        size = in.size();
        while ((dp = out.transferFrom(in, p, size)) > 0)
        {
            p += dp;
        }
    }
    finally {
        try
        {
            if (out != null) out.close();
        }
        finally {
            if (in != null) in.close();
        }
    }
}根据我的测试,带缓冲区的NIO复制最快。请参阅以下我的测试项目中的工作代码,网址为https://github.com/mhisoft/fastcopy
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
public class test {
private static final int BUFFER = 4096*16;
static final DecimalFormat df = new DecimalFormat("#,###.##");
public static void nioBufferCopy(final File source, final File target )  {
    FileChannel in = null;
    FileChannel out = null;
    double  size=0;
    long overallT1 =  System.currentTimeMillis();
    try {
        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(target).getChannel();
        size = in.size();
        double size2InKB = size / 1024 ;
        ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER);
        while (in.read(buffer) != -1) {
            buffer.flip();
            while(buffer.hasRemaining()){
                out.write(buffer);
            }
            buffer.clear();
        }
        long overallT2 =  System.currentTimeMillis();
        System.out.println(String.format("Copied %s KB in %s millisecs", df.format(size2InKB),  (overallT2 - overallT1)));
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        close(in);
        close(out);
    }
}
private static void close(Closeable closable)  {
    if (closable != null) {
        try {
            closable.close();
        } catch (IOException e) {
            if (FastCopy.debug)
                e.printStackTrace();
        }    
    }
}}
快速且可与所有Java版本以及Android一起使用:
private void copy(final File f1, final File f2) throws IOException {
    f2.createNewFile();
    final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
    final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
    file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
    file1.close();
    file2.close();
}晚会晚了一点,但这是使用各种文件复制方法复制文件所花费时间的比较。我遍历了10次方法,取了平均值。使用IO流的文件传输似乎是最糟糕的选择:
方法如下:
private static long fileCopyUsingFileStreams(File fileToCopy, File newFile) throws IOException {
    FileInputStream input = new FileInputStream(fileToCopy);
    FileOutputStream output = new FileOutputStream(newFile);
    byte[] buf = new byte[1024];
    int bytesRead;
    long start = System.currentTimeMillis();
    while ((bytesRead = input.read(buf)) > 0)
    {
        output.write(buf, 0, bytesRead);
    }
    long end = System.currentTimeMillis();
    input.close();
    output.close();
    return (end-start);
}
private static long fileCopyUsingNIOChannelClass(File fileToCopy, File newFile) throws IOException
{
    FileInputStream inputStream = new FileInputStream(fileToCopy);
    FileChannel inChannel = inputStream.getChannel();
    FileOutputStream outputStream = new FileOutputStream(newFile);
    FileChannel outChannel = outputStream.getChannel();
    long start = System.currentTimeMillis();
    inChannel.transferTo(0, fileToCopy.length(), outChannel);
    long end = System.currentTimeMillis();
    inputStream.close();
    outputStream.close();
    return (end-start);
}
private static long fileCopyUsingApacheCommons(File fileToCopy, File newFile) throws IOException
{
    long start = System.currentTimeMillis();
    FileUtils.copyFile(fileToCopy, newFile);
    long end = System.currentTimeMillis();
    return (end-start);
}
private static long fileCopyUsingNIOFilesClass(File fileToCopy, File newFile) throws IOException
{
    Path source = Paths.get(fileToCopy.getPath());
    Path destination = Paths.get(newFile.getPath());
    long start = System.currentTimeMillis();
    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
    long end = System.currentTimeMillis();
    return (end-start);
}使用NIO通道类时看到的唯一缺点是,我似乎仍然找不到找到中间文件复制进度的方法。