How to get a files last changed time (Unix + Java) How to get a files last changed time (Unix + Java) unix unix

How to get a files last changed time (Unix + Java)


Managed to find a slow solution. Copying it in here in case someone has the same issue in future.

//Get time since epoch for a fileprivate static long getLastChanged(final String fileName) {    try {        ProcessBuilder processBuilder = new ProcessBuilder("stat", fileName, "-c", "%Z");        Process process = processBuilder.start();        int errorCode = process.waitFor();        if (errorCode == 0) {            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));            String line;            while ((line = bufferedReader.readLine()) != null) {                return Integer.parseInt(line);            }        } else {            System.out.println("Stat failed with error message: " + errorCode);        }    } catch (Exception e) {        System.out.println("Failed to do stat on file: " + e);    }    return 0;}


You need to use java NIO.2 features.NIO.2 comes with BasicFileAttributeView.

BasicFileAttributeView supports following attributes to get the information

"basic:creationTime” The exact time when the file was created.“basic:lastAccessTime” The last time when the file was accesed.“basic:lastModifiedTime” The time when the file was last modified.

It seems there is no Change time (Change time gets updated when the file attributes are changed, like changing the owner, changing the permission or moving it to another filesystem, but will also be updated when you modify a file.) option available in java.But We can achive through directly execute unix command and parse the result.Sample code snippets

 String command []  = String new String [] {"stat" , "filename"} ;   Process process = new ProcessBuilder(args).start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);