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 "));}}