Java 7 and the Files API

23 Jan 2013

tags: rant, java, jdk, jre, files, copy, isreadable, canread, file, nio, code

I was happy about the fact that Oracle decided to reiterate their grasp on handling Files in Java 7.

So, there are mainly the new classes java.nio.file.Files and java.nio.file.PathFiles provides methods like isDirectory, exists, isReadable or copy. While the first of them are familiar from, copy is new and allows for native-like performance when copying data. I haven't performed any specific Benchmarks, but research suggests they are more lightweight when used heavily and use the native OS functions for copying stuff. Also, handling symlinks seems to be prettier now.

Getting to the point: Beware of java.nio.file.Files.isReadable()! When converting tuSync to this new API, I noticed my code for checking my filebase had gotten really slow. Some profiling later, I found the culprit.
When checking about 10,000 files for read access, my profiler showed me this:

Method            --            Avg. time (ms)          
-- 0.0333
java.nio.Files.isReadable()   -- 2.5679

Which means it takes about 80 times longer for Files.isReadable() to return.

According to this, which is my current system (Win7 x64), I am encountering a bug, which is already fixed. So if you run into this problem, either use the workaround path.getFileSystem().provider().checkAccess(path) or the old method, because it does exactly the same.

If you are in the future and Java 8 is out, you can happily update your JDK and move along to, like, attending to serious problems.

Some possibly related posts: