您的位置:首页 > 其它

使用FileChannel实现文件复制

2018-01-10 00:05 295 查看
今天在资深开发者交流,遇到了FileChannel,亲测,在进行文件复制时效果比BufferedInputStream速度要快。

值得一提的是FileChannel在使用前,必须要打开。需要通过InputStream/OutputStream/RandomAccessFile获取,BufferedReader/BufferedWriter获取不到。

* @see java.io.FileInputStream#getChannel()
* @see java.io.FileOutputStream#getChannel()
* @see java.io.RandomAccessFile#getChannel()


使用FileChannel进行文件复制

public static void fileChannelCopy(File src,File dst) throws IOException {
FileChannel inChannel =new FileInputStream(src).getChannel();
FileChannel outChannel=new FileOutputStream(dst).getChannel();

inChannel.transferTo(0, inChannel.size(), outChannel);

inChannel.close();
outChannel.close();
}
使用普通BufferedInputStream进行文件复制

public static void bufferedCopy(File src,File dst) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dst));
int line=0;
byte[] buf=new byte[1024*10];
while((line=bis.read(buf))!=-1) {
bos.write(buf);
}
bis.close();
bos.close();
}
测试(文件大小1G+)

public static void main(String[] args) throws IOException {
File src = new File("E:\\myCode\\kaifa.txt");
File dstFileChannel = new File("E:\\myCode\\kaifa1.txt");
File dstBufferd = new File("E:\\myCode\\kaifa2.txt");

long start = System.currentTimeMillis();
fileChannelCopy(src, dstFileChannel);
long end = System.currentTimeMillis();
System.out.println("fileChannelCopy: " + (end - start) + " ms");

start = System.currentTimeMillis();
bufferedCopy(src, dstBufferd);
end = System.currentTimeMillis();
System.out.println("bufferedCopy " + (end - start) + " ms");
}
我们来比对二者时间消耗

fileChannelCopy: 26370 ms
bufferedCopy 38101 ms
记在最后:

FileChannel是线程安全的,这就在很多场合我们可以很好的利用这一性能

* <p> File channels are safe for use by multiple concurrent threads.  The
* {@link Channel#close close} method may be invoked at any time, as specified
* by the {@link Channel} interface.  Only one operation that involves the
* channel's position or can change its file's size may be in progress at any
* given time; attempts to initiate a second such operation while the first is
* still in progress will block until the first operation completes.  Other
* operations, in particular those that take an explicit position, may proceed
* concurrently; whether they in fact do so is dependent upon the underlying
* implementation and is therefore unspecified.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: