Java Thread That Will Look for New File Even After Program Has Ended


In this post, I will be showing you how to write a thread program that will keep running even after the main program has ended, and will show files at a particular location that will keep updating after you add any new files into the folder.

Prerequisite:

  • Eclipse IDE
  • Java 1.8

Steps:

  • Right click on your project in Package Explorer, click New > Class.

Leave the package name for now and let it be default. Type any class name in the Name field, check the public static void main(String[] args) checkbox and click Finish.

  • Right-click on your project again, click New > Folder.
Name the folder as "Files". Paste here your files in this folder. For now lets paste 1 file.
  • Suppose let's name the class:

Class: BackgroundRunningThread.java
Code:
import java.io.File;

public class BackgroundRunningThread {

  public static void main(String[] args) {
    Runnable r = new Runnable() {

      @Override
      public void run() {
        boolean flag = true;
        while (flag) {
          File dir = new File("Files");
          File[] files = dir.listFiles();
          for (File file: files) {
            String fileName = file.getName();
            System.out.println(fileName);
          }
          try {
            Thread.sleep(2000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    };
    Thread t = new Thread(r);
    t.start();
    System.out.println("Main() program exited already\n");
  }
}

Now even if you add new files into your Files folder, this thread will keep running for infinite time ( as while(true)) and new file's name will get printed on the console.


     


Comments