4 ways to copy files in Java

Source: Internet
Author: User

First, using FileStreams copy

This is the most classic way to copy the contents of a file to another file. Use FileInputStream to read the bytes of file a, using FileOutputStream to write to file B. This is the code for the first method:

1 private static void Copyfileusingfilestreams (file source, file dest) 2         throws IOException {     3     inputstream I Nput = null;     4     OutputStream output = null;     5     try {6            input = new FileInputStream (source); 7            output = new FileOutputStream (dest);         8            byte[] buf = new byte[1024];         9            int bytesread;        Ten while            (bytesread = Input.read (BUF))! =-1) {One                output.write (buf, 0, bytesread);            }13     } finally {         input.close ();         Output.close ();     }17}

As you can see, we perform several read and write operations to try the data, so this should be a inefficient one, and the next method we will see is the new way.

Second, use FileChannel copy

Java NiO includes the Transferfrom method, which should be faster to copy than file stream according to the document. Here is the code for the second method:

1 private static void Copyfileusingfilechannels (file source, file dest) throws IOException {     2         filechannel INPUTC Hannel = null;     3         FileChannel outputchannel = null;     4     try {5         Inputchannel = new FileInputStream (source). Getchannel (); 6         Outputchannel = new FileOutputStream ( dest). Getchannel (); 7         outputchannel.transferfrom (inputchannel, 0, Inputchannel.size ()); 8     } finally {9         inputchannel.close ( );         outputchannel.close ();     }12}
Third, using commons IO Replication

Apache Commons IO provides a copy file method in its Fileutils class, which can be used to copy a file to another place. It is very handy when you use the Apache Commons Fileutils class when you have used your project. Basically, this class uses Java NIO filechannel inside. This is the code for the third method:

1 private static void Copyfileusingapachecommonsio (file source, file dest) 2         throws IOException {3     Fileutils.copyfile (source, dest); 4}

The core code of the method is as follows:

 1 private static void Docopyfile (file srcfile, File DestFile, Boolean preservefiledate) throws IOException {2 if (Destfile.exists () && destfile.isdirectory ()) {3 throw new IOException ("Destination" + destfile + "' exists but is a directory"); 4} 5 6 FileInputStream FIS = null; 7 FileOutputStream fos = null; 8 FileChannel input = null;  9 FileChannel output = null;10 try {One FIS = new FileInputStream (srcfile); fos =             New FileOutputStream (destfile); input = Fis.getchannel (); output = Fos.getchannel (); 15 A Long size = Input.size (), and a long pos = 0;17 Long Count = 0;18 while (Pos < s ize) {count = size-pos > file_copy_buffer_size?         file_copy_buffer_size:size-pos;20 pos + = Output.transferfrom (input, POS, count); 21}22 } finally {IOUtils.closequietly (output), ioutils.closequietly (FOS), ioutils.closequietly (input); 26  ioutils.closequietly (FIS);}28 if (srcfile.length ()! = Destfile.length ()) {+ throw new         IOException ("Failed to copy full contents from '" +31 srcfile + "' to '" + destfile + "'"); 32 }33 if (preservefiledate) {destfile.setlastmodified (srcfile.lastmodified ()); 35}36}

Thus, the principle of copying files using Apache Commons Io is the second method described above: using FileChannel replication

Iv. files class replication using Java7

If you have some experience in Java 7 You might know that you can use the Copy method of the files class file to copy from one file to another. This is the code for the fourth method:

1 private static void Copyfileusingjava7files (file source, file dest) 2         throws IOException {    3         files.copy ( Source.topath (), Dest.topath ()); 4}

V. Testing

Now see which of these methods is more efficient, we will copy a large file using each one in a simple program. From cache to avoid any performance obviously we will use four different source files and four different target files. Let's take a look at the code:

 1 Import java.io.File; 2 Import Java.io.FileInputStream; 3 Import Java.io.FileOutputStream; 4 Import java.io.IOException; 5 Import Java.io.InputStream; 6 Import Java.io.OutputStream; 7 Import Java.nio.channels.FileChannel; 8 Import Java.nio.file.Files; 9 Import org.apache.commons.io.fileutils;10 One public class Copyfilesexample {All public static void main (string[] A RGS) throws interruptedexception,14 IOException {File Source = new file ("C:\\users\\nikos7\\desk         Top\\files\\sourcefile1.txt "); file Dest = new file (" C:\\users\\nikos7\\desktop\\files\\destfile1.txt "); 18 19 Copy file using Filestreamslong start = System.nanotime (); Long end;21 Copyfileusingfilestreams (source, dest); System.out.println ("Time taken by filestreams Copy =" + (System.nanotime ()- Start));//copy files using Java.nio.FileChannelsource = new File ("C:\\users\\nikos7\\desktop\\files\\source File2.txt "); 26         Dest = new File ("C:\\users\\nikos7\\desktop\\files\\destfile2.txt"); start = System.nanotime (); 28  Copyfileusingfilechannels (source, dest); end = System.nanotime (); System.out.println ("Time taken by Filechannels copy = "+ (End-start));//Copy file using Java 7 Files classsource = new File (" c:\\users\\n          Ikos7\\desktop\\files\\sourcefile3.txt "), dest = new File (" C:\\users\\nikos7\\desktop\\files\\destfile3.txt "); 34         Start = System.nanotime (); Copyfileusingjava7files (source, dest); + end = System.nanotime (); 37 System.out.println ("Time taken by Java7 files Copy =" + (End-start));//Copy Files using Apache C Ommons iosource = new File ("C:\\users\\nikos7\\desktop\\files\\sourcefile4.txt"), dest = new File ("C:\\users\\ni  Kos7\\desktop\\files\\destfile4.txt "); start = System.nanotime (); Copyfileusingapachecommonsio (source, DEST);System.nanotime (); System.out.println ("Time taken by Apache Commons IO Copy =" + (End-start );}48, copyfileusingfilestreams (file source, file dest), throws Ioexcept Ion {InputStream input = null;52 outputstream output = null;53 try {si input = new             FileInputStream (source), output = new FileOutputStream (dest), byte[] buf = new byte[1024];57  int bytesread;58 while ((Bytesread = Input.read (buf)) > 0) {output.write,         0, Bytesread);}61} finally {input.close (); Output.close (); 64  }65}66, private static void Copyfileusingfilechannels (file source, file dest), throws IOException {FileChannel Inputchannel = null;70 FileChannel Outputchannel = null;71 try {in Putchannel = new FILEINPUtstream (source). Getchannel (); outputchannel = new FileOutputStream (dest). Getchannel ();             Channel.transferfrom (inputchannel, 0, Inputchannel.size ()); finally {inputchannel.close (); 77 Outputchannel.close ();}79}80 Bayi private static void Copyfileusingjava7files (File source, Fil E dest) throws IOException {files.copy (Source.topath (), Dest.topath ());}85 static void Copyfileusingapachecommonsio (file source, file dest) throws IOException {fileutils.co Pyfile (source, dest); 89}90 91}

Output:

Time taken by filestreams copy = 127572360Time taken by filechannels copy = 10449963Time taken by Java7 Files Copy = 10808 333Time taken by Apache Commons IO Copy = 17971677

As you can see, filechannels copying large files is the best method. If you deal with larger files, you will notice a greater speed difference. This is an example that shows four different ways in Java that you can copy a file.

4 ways to copy files in Java

Related Article

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.