Compare the performance of new and old java I/O-Take copying large files as an Example

Source: Internet
Author: User

Compare the performance of new and old java I/O-Take copying large files as an Example

Package newio; import java. io. *; import java. nio. byteBuffer; import java. nio. channels. fileChannel;/** use APIs of the New and Old I/O packages respectively to copy files, and compare performance */public class CopyFileCompara {public void copyFileOld (File from, File) throws IOException {// use the traditional I/O Stream processing (with a buffer mechanism) FileInputStream fin = new FileInputStream (from); FileOutputStream fout = new FileOutputStream (); bufferedInputStream in = new BufferedInputStream (fin); BufferedOutputStr Eam out = new BufferedOutputStream (fout); int B; long start = System. currentTimeMillis (); while (B = in. read ())! =-1) {out. write (B);} long cost = (System. currentTimeMillis ()-start)/1000; System. out. println ("old I/O (buffer used) Time consumed:" + cost + "s"); out. close (); in. close ();} public void copyFileNew (File from, File to) throws IOException {// Use Channel and Buffer to process FileChannel fin = new FileInputStream (from ). getChannel (); FileChannel fout = new FileOutputStream (). getChannel (); long start = System. currentTimeMillis (); ByteBuffer bfi = fin. map (FileChannel. mapMode. READ_ONLY, 0, from. length (); fout. write (bfi); long cost = (System. currentTimeMillis ()-start)/1000; System. out. println ("New I/O time:" + cost + "s"); fout. close (); fin. close ();} public static void main (String [] args) throws IOException {// a larger copy of the file will better reflect the effect of new CopyFileCompara (). copyFileOld (new File ("F: \ 01 lecture 1. wmv "), new File (" F :\\ copy 1.wmv"); new CopyFileCompara (). copyFileNew (new File ("F: \ 01 lecture 1. wmv "), new File (" F :\\ copy 2.wmv "));}}

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.