Java Program Calculate Time Taken To Copy A File

Copy file to shared folder java

In this article we will discuss about finding the time taken to copy a file from one path to other. This program is useful in debugging issues where any java application is taking too much time to upload any attachments or in copying a file from temporary folder to permanent attachment or copy file shared folder java.

In our scenario upload of attachment to application was very slow and we found that attachment upload to temp folder and encryption was super fast but copy to shared attachment folder was very slow. Due to this we had to develop a sample program to see what is the actual time it takes to copy from a temp folder to shared/mounted attachment folder.

Save below java file as CopyingFile.java and compile with any JDK using javac CopyingFile.java

To run test follow below steps:

  1. Copy the CopyingFile.class to the host
  2. Run the program like java CopyingFile C:\Tomcat\Files\Softwares\testfile.avi \\fileserver\attachments\testfile.avi
  3.  Once copy is complete the output will show time taken in nano seconds.

Sample Output:

E:\Jre\bin>java CopyingFile C:\Tomcat\Files\Softwares\testfile.avi \\fileserver\attachments\testfile.avi

cp C:\Tomcat\Files\Softwares\testfile.avi \\fileserver\attachments\testfile.avi
The file has been copied using java
Time taken to copy in nano seconds = 428774300

Copy file to shared folder java Program:

import java.io.FileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;



public class CopyingFile
{
    public static void main(final String[] array) throws IOException {
        final String s = array[0];
        final String s2 = array[1];
        System.out.println("cp " + array[0] + " " + array[1]);
		long start = System.nanoTime();
        copyFile(s, s2);
		System.out.println("The file has been copied using java");
		System.out.println("Time taken to copy in nano seconds  = "+(System.nanoTime()-start));
    }
    
    public static void copyFile(final String pathname, final String name) throws IOException {
        final FileOutputStream fileOutputStream = new FileOutputStream(name);
        final FileInputStream fileInputStream = new FileInputStream(new File(pathname));
        final byte[] array = new byte[16777216];
        int read;
        while ((read = fileInputStream.read(array)) > 0) {
            fileOutputStream.write(array, 0, read);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.