1、使用 NIO(Java NIO):
Java NIO提供了一组类,它们比传统IO 类提供更快、更高效的文件操作。
您可以使用Files.copy()方法使用 NIO 复制文件。
这种方法利用了本机操作系统的文件复制机制,可以比逐字节复制文件快得多。
// 路径:该类由静态方法组成,通过转换路径字符串或 URI 返回路径; |
2、使用缓冲流:
在 Java 中复制文件的另一种方法是使用缓冲流。缓冲流使用内部缓冲区读写数据,可以减少所需的 I/O 操作次数并提高性能。
File crunchifySource = new File("path/to/source/file"); |
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();
}
}
}