user2935569
user2935569

Reputation: 347

Comparing current date time(live) with file last modified

I want my program output such that, whenever it receives a text file from a client, It will print "A new file has been received!". The text files will be store in C:/Users/%UserProfile%/Desktop/ad.

The code below is to check whether a new text file has been received into the directory.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.Timer;


public class Test {

    final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    static int count = 0;
    static File[] f = null;
    static Date date = new Date();  
    static Calendar now = null;

    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        while(true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            f = new File("C:/Users/roberts/Desktop/ad").listFiles();
            int l = f.length;
            System.out.println("There are " +  l +  " files in the directory");

            for (int i = 0; i < l; i++) {
                System.out.println("file " + i +  " date modified " + dateFormat.format(f[i].lastModified()));
            }
        }
    }
}

Output of total number of files in the directory initially = 1 and last modified

enter image description here

Output of total number of files in the directory after file is received = 2 and last modified

enter image description here

Now in order to print "A new file has been received!" I need to compare the current date time with the last modified date time of the file.

This is what I did

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.Timer;


public class Test {

    final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    int interval = 1000;
    static int count = 0;
    static File[] f = null;
    static Date date = new Date();  
    static Calendar now = null;

    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        while(true) {

                f = new File("C:/Users/roberts/Desktop/ad").listFiles();
                int l = f.length;
                System.out.println(l);
                new Timer(1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        now = Calendar.getInstance();
                        for (int i = 0; i < l; i++) {
                            if(dateFormat.format(now.getTime()).equals(dateFormat.format(f[i].lastModified()))) {
                                System.out.println("A new file has been received!");
                            }
                        }

                    }
                }).start();

            try {
                Thread.currentThread().join();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
}

I tried but it doesn't print "A new file has been received!". Please help

Upvotes: 1

Views: 8581

Answers (2)

bvdb
bvdb

Reputation: 24770

Watching file system changes is best done using the Watch Service. Right now you are polling for file changes, but instead the watch service uses native windows events.

First you just need to create an instance of the WatchService class.

Path path = Paths.get("c:\mydir");
WatchService service = path.getFileSystem().newWatchService();

Next you have to decide what kind of events you want to monitor. I think you only want to be informed when new files appear in the folder.

path.register(service, StandardWatchEventKinds.ENTRY_CREATE);

Next, the service acts like a buffer of events. I suggest to put the processing of this buffer in a seperate thread.

// repeat forever
for (;;)
{
  // this will block until there's something inside the buffer
  WatchKey key = service.take();

  // 1 watchkey can contain multiple events, you need to iterate these.
  for (WatchEvent<?> event : key.pollEvents())
  {
    //todo: handle events
  }
}

Upvotes: 1

Forketyfork
Forketyfork

Reputation: 7810

This is because your while(true) loop does not loop, so your code that checks the size of the directory works only once, and variable l stays the same. You block the thread forever with a call to Thread.currentThread().join() (current thread blocks until current thread stops, i.e. forever). The Timer fires once every 1000 ms, but since l does not change, it finds no new files.

If you want to simply watch directory for changes, instead of reinventing the wheel, you better use standard JDK class https://docs.oracle.com/javase/8/docs/api/java/nio/file/WatchService.html

Upvotes: 0

Related Questions