java 代码复制_【代码记录】Java文件复制

package test;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.channels.FileChannel;

import java.nio.file.Files;

import org.apache.commons.io.FileUtils;public classtest {public static voidmain(String[] args) throws Exception{

File source=new File("D:\\MyLearningNotes\\test.txt");

File dest1=new File("D:\\MyLearningNotes\\test1.txt");

File dest2=new File("D:\\MyLearningNotes\\test2.txt");

File dest3=new File("D:\\MyLearningNotes\\test3.txt");

File dest4=new File("D:\\MyLearningNotes\\test4.txt");

copyFileUsingFileStreams( source, dest1);

copyFileUsingFileChannels(source, dest2);

copyFileUsingJava7Files(source, dest3);

copyFileUsingApacheCommonsIO(source, dest4);

}//1.Java流和File类

private static voidcopyFileUsingFileStreams(File source, File dest)

throws IOException {

InputStream input= null;

OutputStream output= null;try{

input= newFileInputStream(source);

output= newFileOutputStream(dest);byte[] buf = new byte[1024];intbytesRead;while ((bytesRead = input.read(buf)) > 0) {

output.write(buf,0, bytesRead);

}

}finally{

input.close();

output.close();

}

}//2.java.nio.channels.FileChannel类

private static voidcopyFileUsingFileChannels(File source, File dest) throws IOException {

FileChannel inputChannel= null;

FileChannel outputChannel= null;try{

inputChannel= newFileInputStream(source).getChannel();

outputChannel= newFileOutputStream(dest).getChannel();

outputChannel.transferFrom(inputChannel,0, inputChannel.size());

}finally{

inputChannel.close();

outputChannel.close();

}

}//3.Java7 java.nio.file.Files类

private static voidcopyFileUsingJava7Files(File source, File dest)

throws IOException {

Files.copy(source.toPath(), dest.toPath());

}//4.org.apache.commons.io.FileUtils类

private static voidcopyFileUsingApacheCommonsIO(File source, File dest)

throws IOException {

FileUtils.copyFile(source, dest);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值