你好,大家好我有一個如何在背景中的JavaFXJavaFX中運行的後臺任務
運行任務的一個問題目前的情況是,我已經創造了JavaFX的複印功能,它是工作精絕,但如果我們有更多的文件,那麼它將進入無響應模式,直到過程完成,日誌也不會打印在我的textarea中,每個文件都被複制到相應的文件夾中,但問題是它會一直掛起,直到過程完成,
還有一個問題,如何永遠運行這個程序意味着每當一個新文件進入源目錄時,它就會自動進入目標目錄。
這裏是我的代碼
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();
}
這是複印功能
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();
}
}
記得撥打['exService.shutdown()'](https://docs.oracle.com/javase/8/docs/api /java/util/concurrent/ExecutorService.html#shutdown--)在某個階段(通常是應用程序的['stop()'](https://docs.oracle.com/javase/8/javafx/api/javafx/ application/Application.html#stop--)方法),以便在不再需要執行程序服務時關閉該程序,並允許程序正常退出。或者,或者使用提供守護程序線程的新線程工廠創建ExecutorService。 – jewelsea