4

In Unix there is a difference between last changed time and last modifies time. For example when using stat I can get:

Access: 2016-01-18 10:50:01.624303144 +0100
Modify: 2016-01-12 13:34:18.274639073 +0100
Change: 2016-01-15 13:13:52.881401711 +0100

When I program in Java I can easily get the last modification time. But how do I get the last change time of a file?

Arenlind
  • 53
  • 5
  • It appears that attribute isn't supported in any FileAttributeView yet. Only "lastAccessTime", "creationTime" and "lastModifiedTime" are available. That "change" time would be when metadata such as permissions last changed. – uncaught_exception Jan 18 '16 at 11:27
  • Correct. I assume it is so because Java must support all OS's. But it feels like it should somehow be possible to ask for specific attributes from one OS – Arenlind Jan 18 '16 at 11:52

2 Answers2

1

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 file
private 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;
}
Arenlind
  • 53
  • 5
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);
Pankaj Pandey
  • 1,015
  • 6
  • 10