Different methods have a great impact on large files when replicating with different reading and writing methods.
Here are three ways to test it.
Ps:System.currentMillis (); Used to record the time of the moment.
1. Direct replication using a single byte (slow speed)
The implementation method is as follows
Public Static voidDZJ (File infile,file outfile)throwsioexception{FileInputStream in=NewFileInputStream (infile); FileOutputStream out=NewFileOutputStream (outfile); if(!infile.exists ())Throw NewIllegalArgumentException ("This file does not exist"); if(!infile.isfile ())Throw NewIllegalArgumentException ("This file is not a directory"); LongA=System.currenttimemillis (); inti; while((I=in.read ())!=-1) {out.write (i); Out.flush (); } Longb=System.currenttimemillis (); System.out.println ("Single byte direct copy time" + (b-a)); In.close (); Out.close ();}
2. Use buffer bufferef to improve performance (speed is significantly improved)
Public Static voidHC (File infile,file outfile)throwsioexception{Bufferedinputstream in=NewBufferedinputstream (NewFileInputStream (infile)); Bufferedoutputstream out=NewBufferedoutputstream (NewFileOutputStream (outfile)); if(!infile.isfile ())Throw NewIllegalArgumentException ("This is not a file"); if(!infile.exists ())Throw NewIllegalArgumentException ("File does not exist"); LongA=System.currenttimemillis (); inti; while((I=in.read ())!=-1) {out.write (i); Out.flush (); } Longb=System.currenttimemillis (); System.out.println (The time to read and write buffers is: "+ (B-a)); In.close (); Out.close ();}
3. Byte array bulk Read and write bytes (speed increase is very obvious, open up memory)
Public Static voidBytes (File infile,file outfile)throwsioexception{FileInputStream in=NewFileInputStream (infile); FileOutputStream out=NewFileOutputStream (outfile); if(!infile.exists ())Throw NewIllegalArgumentException ("File does not exist"); if(!infile.isfile ())Throw NewIllegalArgumentException ("Not File"); LongA=System.currenttimemillis (); intbytes; byte[]buf=New byte[20*1024]; while((Bytes=in.read (buf,0,buf.length))!=-1) {out.write (buf,0, bytes); Out.flush (); } Longb=System.currenttimemillis (); System.out.println ("The byte array method takes:" + (B-a)); In.close (); Out.close ();}
The result of the above code operation is as follows:
Test file is 10.1 MB (10,616,738 bytes)
IO---Java different read and write mode IO performance