Thursday, September 29, 2011

Java class to test whether a file is in copying state or ready state

The following Java utility class could be used to test whether a file is in Copying state or it has been copied to file system. The class uses java scanner class. An infinite loop is used and upon each check the thread goes to sleep for 10 seconds. When the copying is completed the loop breaks.



/**
 * 
 */
package com.bishal.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * @author bishal acharya
 * This class is used to test whether a file is in copy state
 *         or Ready state.
 */
public class CopyProgress {

    private boolean isFileReady(String filePath) {
        File file = new File(filePath);

        Scanner scanner;
        boolean isCopying = true;
        while (true) {
            try {
                scanner = new Scanner(file);
                isCopying = false;
            } catch (FileNotFoundException e) {
                System.out.println("File not found or is in copy State. ");
                sleepThread();
            }
            if (isCopying == false) {
                break;
            }
        }
        System.out.println("copy completed ::");
        return isCopying;
    }

    /**
     * sleep for 10 seconds
     */
    private static void sleepThread() {
        System.out.println("sleeping for 10 seconds");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        CopyProgress cp = new CopyProgress();
        cp.isFileReady("C:\\Documents and Settings\\bacharya\\My Documents\\videos\\Se7en.avi");
    }
}





Check Output : The output for the project would be

File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
File is in copy State.
sleeping for 10 seconds
copy completed ::

1 comment:

Anonymous said...

Very cool. This was useful for me. Thanks.