Search code examples
javajavafxbackground-process

Running a background Task in javafx


Hello Guys I have a question that how to run the task in background in Javafx

Currently the situation is that I have created a Copy Function in javafx, it is working absolutely fine, but if we have more files, then it goes in not responding mode till the process completes, Logs are also not printed in my textarea, Every file is being copied in the respected folder, but the problem is its hanged till the process completes,

And One more question how to run this program forever means whenever a new file comes in source directory it automatically goes to the destination directory.

Here is my code

try
        {
            sourceFile = new File(sourcePath).listFiles();
            syslog.appendText("\nTotal Files in the Directory : " + sourceFile.length);
            for(int i = 0; i<sourceFile.length;i++)
            {
                if(sourceFile[i].isFile())
                {
                    String file = sourceFile[i].getName();
                    String extension = Files.getFileExtension(file);
                    if(!new File(destinationPath+"/"+extension.toUpperCase()).exists())
                    {
                        if(new File(destinationPath+"/"+extension.toUpperCase()).mkdir())
                        {
                            syslog.appendText("\nDirectory Created : " + destinationPath+"/"+extension.toUpperCase());
                            try
                            {
                                if(!new File(destinationPath+"/"+extension.toUpperCase()+"/"+file).exists())
                                {
                                    syslog.appendText("\nFile "+file+" is processing to copy to "+destinationPath+"/"+extension.toUpperCase());
                                    copyFile(sourceFile[i],new File(destinationPath+"/"+extension.toUpperCase()+"/"+file));
                                    syslog.appendText("\nFile "+file+" is successfully copied to "+destinationPath+"/"+extension.toUpperCase());
                                    if(sourceFile[i].delete())
                                        syslog.appendText("\nFile "+file+" is successfully deleted from "+sourcePath);
                                    else
                                        syslog.appendText("\nError in deleting File "+file+" from "+sourcePath);
                                }
                            }
                            catch(Exception e)
                            {
                                e.printStackTrace();
                                syslog.appendText("\nSome Error Occurred while copying the File : "+sourceFile[i]);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            if(!new File(destinationPath+"/"+extension.toUpperCase()+"/"+file).exists())
                            {
                                syslog.appendText("\nFile "+file+" is processing to copy to "+destinationPath+"/"+extension.toUpperCase());
                                copyFile(sourceFile[i],new File(destinationPath+"/"+extension.toUpperCase()+"/"+file));
                                syslog.appendText("\nFile "+file+" is successfully copied to "+destinationPath+"/"+extension.toUpperCase());
                                if(sourceFile[i].delete())
                                    syslog.appendText("\nFile "+file+" is successfully deleted from "+sourcePath);
                                else
                                    syslog.appendText("\nError in deleting File "+file+" from "+sourcePath);
                            }
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                            syslog.appendText("\nSome Error Occurred while copying the File : "+sourceFile[i]);
                        }
                    }
                }
            }
            syslog.appendText("\nFinished..........");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

And this is the copy Function

    private static void copyFile(File source, File destination)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(destination).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

Solution

  • You need to create a Task and add it to a new thread. It looks like this:

            Task<T> backgroundTask = new Task<T>() {
            @Override
            protected T call() throws Exception {
                return null;
            }
    
            @Override
            public void run() {
                try {
                        copyFile(source,destination); //or any other operation you want to have in a thread.
                            } catch (IOException e) {
                               e.printStackTrace();
                            }
                    }
            }
        };
        Thread backgroundThread = new Thread(backgroundTask);
        backgroundThread.setDaemon(true); //true if you want to have it running excuslivly when having your parent-threat running
    

    You can call and run this thread once with

     backgroundThread.run();
    

    Futher you can check the state of the thread with

     backgroundThread.state();
    

    which could be helpful if you want to check e.g. if your thread is still in process.

    Consider collisions with your javafx-thread. If you want to alter a object which is accessed by the javafx-thread you need to perform a

     Platform.runLater(new Runnable() {/*your impact on javafx*/});