Java中复制文件三种最简单、最快的方法

在 Java 中复制文件的方法有多种,但最快的方法取决于多种因素,例如文件的大小、可用的系统资源以及所需的并发级别。

1、使用 NIO(Java NIO):
Java NIO提供了一组类,它们比传统IO 类提供更快、更高效的文件操作。
您可以使用Files.copy()方法使用 NIO 复制文件。
这种方法利用了本机操作系统的文件复制机制,可以比逐字节复制文件快得多。

 

  // 路径:该类由静态方法组成,通过转换路径字符串或 URI 返回路径;
            Path crunchifySource = Paths.get("path/to/source/file");
            Path crunchifyTarget = Paths.get("path/to/target/file");
            
            // 文件:该类完全由对文件、目录或其他类型的文件进行操作的静态方法组成:复制文件到目标文件。
          //该方法将文件复制到目标文件,选项参数指定了复制的方式。 
          // 默认情况下,如果目标文件已经存在或者是符号链接,复制将失败,除非源文件和目标文件是同一个文件, 
          // 在这种情况下,方法完成后不会复制文件。文件属性不需要复制到目标文件。 
          // 如果支持符号链接,并且文件是一个符号链接,那么链接的最终目标将被复制。 
          // 如果文件是目录,则在目标位置创建一个空目录(目录中的条目不会被复制)。 
          // 该方法可与 walkFileTree 方法一起使用,以复制一个目录和目录中的所有条目,或根据需要复制整个文件树。
            Files.copy(crunchifySource, crunchifyTarget, StandardCopyOption.REPLACE_EXISTING);


2、使用缓冲流:
在 Java 中复制文件的另一种方法是使用缓冲流。缓冲流使用内部缓冲区读写数据,可以减少所需的 I/O 操作次数并提高性能。

 File crunchifySource = new File("path/to/source/file");
            File crunchifyTarget = new File("path/to/target/file");
           // BufferedInputStream:创建缓冲输入流(BufferedInputStream),并保存其参数(输入流)以备后用。
            // 创建内部缓冲数组并将其保存在 buf 中。
            try (InputStream in = new BufferedInputStream(new FileInputStream(crunchifySource));
                 
                 // BufferedOutputStream:创建新的缓冲输出流,将数据写入指定的底层输出流。
               OutputStream out = new BufferedOutputStream(new FileOutputStream(crunchifyTarget))) {
                byte[] crunchifyBuffer = new byte[1024];
                int crunchifyLengthRead;
                while ((crunchifyLengthRead = in.read(crunchifyBuffer)) > 0) {
                    out.write(crunchifyBuffer, 0, crunchifyLengthRead);
                }
            }
        }


3、使用 FileChannel:
如何将 Java 中的文件从一个目录复制到另一个目录是常见的需求。
Java 没有现成的复制文件代码。下面的方法是在 Java 中复制文件的最快方法?

 FileChannel inChannel = new FileInputStream( in ).getChannel();
        FileChannel outChannel = new FileOutputStream( out ).getChannel();
        try
        {
            // 对于 Windows,64Mb - 32Kb)。
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while ( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
            System.out.println("File Successfully Copied..");
        }
        finally
        {
            if ( inChannel != null )
            {
               inChannel.close();
            }
            if ( outChannel != null )
            {
                outChannel.close();
            }
        }
    }