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