Java直接复制文件的方法常用的用四种,大家可以参考一下。
第一种 files.copy工具。
需要引用方法
import java.nio.file.Files;
代码片段:
public static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
第二种:FileUtils.copyFile方法,需要引用jar
commons-io-2.4.jar 有需要的可以去maven仓库里面直接下载,很直接。
代码:
public static void copyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}
第三种:FileChannel方法
主要引入方法:
import java.nio.channels.FileChannel;
代码片段:
public static void copyFileUsingFileChannels(File source, File dest){
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inputChannel.close();
outputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第四种:传统的流输入输出方法
直接贴代码:
public static void copyFileUsingFileStreams(File source,File dest){
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buf)) > 0) {
out.write(buf, 0, bytesRead);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
亲测可用,其中文件较小的情况下建议使用流读出写入方法比较快,文件超过百兆的情况下,FileChannel方法最为迅速,大概是其他三种方法的几倍到几十倍效率。