Java Copy File

Source: Internet
Author: User

In Java programming, there are many ways to copy files, and they are often used. I used to be a buffer input and output stream (which is what most people do), and recently, when researching JDK documents, I found that using file channels (FileChannel) to replicate files was nearly one-third faster than the old method. Let me show you how to use file channels for file copying and efficiency comparisons.

I. File copy with file Channel

 /*** Copy files using the file channel * *@paramS * source file *@paramT * Copy to the new file*/     Public voidfilechannelcopy (file s, file t) {FileInputStream fi=NULL; FileOutputStream fo=NULL; FileChannel in=NULL; FileChannel out=NULL; Try{fi=NewFileInputStream (s); Fo=NewFileOutputStream (t); Inch= Fi.getchannel ();//get the corresponding file channelout = Fo.getchannel ();//get the corresponding file channelIn.transferto (0, In.size (), out);//connect two channels and read from the in channel, then write to an out channel}Catch(IOException e) {e.printstacktrace (); } finally {            Try{fi.close ();                In.close ();                Fo.close ();            Out.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }

Comparison of replication efficiency with normal buffered input and output streams

Normal buffered input and output stream code:

Test code:

Output Result:

This shows that filechannel copying files is nearly one-third faster than bufferedinputstream/bufferedoutputstream copying files. The speed advantage of FileChannel is more evident when copying large files. And FileChannel is more concurrent thread-safe.

Original: http://jingyan.baidu.com/article/ff4116259c2d7712e4823780.html

Java Copy File

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.