File last access time in Java on Linux

Some time ago a friend of mine needed to retrieve last access time of file in his Java code on Linux. Then he used this info to check if some cache files can be removed. I’ve wrote simple JNI based library to do this. It’s very simple but maybe someone can reuse it. So here it is (You need Java 1.4 or newer to use):

Jar with classes: jAccessTimeJ.jar
Native library (32bit): libjAccessTimeC.so

(Sorry no 64bit binary yet. I don’t have 64 bit Linux host right now. Please send it to me if you compile it from sources)

To run:
java -Djava.library.path=./ -cp jAccessTimeJ.jar com.wordpress.jdevel.utils.JAccessTimeUnix /path/to/file

Remember to put .so file in current directory.
Or you could put .so file somewhere on LD_LIBRARY_PATH and then omit -Djava.library.path=./ switch.

To use it from you Java code:

private void testLastAccess() {
    File f = new File("/boot/vmlinuz");
    Date date = JAccessTimeUnix.getLastAccessTime(f);
    System.out.println(date);
}

You can get source from here:
Java-last-access-time-linux

Advertisements

10 Responses to File last access time in Java on Linux

  1. Alan says:

    With jdk7 then you can read all the basic file attributes (including the time stamps) in one method:

    BasicFileAttributes attrs = Files.readAttributes(f.toPath(), BasicFileAttributes.class);
    FileTime lastAccess = attrs.lastAccessTime();

    • Marek Piechut says:

      That’s great. I hope we don’t need it in future projects 🙂 But what we needed is to make it work on 1.5. It was the only supported version for Windchill system we were creating it for.

    • rak says:

      will you please elaborate your codes.

  2. Rami says:

    How can I use the JNI in my java?

  3. Marek Piechut says:

    You need to add folder with .so file to LD_LIBRARY_PATH environment variable or launch java with -Djava.library.path=<> switch.

    There are plenty of JNI manuals online:
    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html
    for example.

  4. rak says:

    where is the .so file I cannot find it.

  5. D says:

    @allan: please provide complete source code

  6. Pingback: JavaPins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: