The previous answer gives a NullPointerException when File object has no path, namely, it is just a filename.
A minor modification works for that case as well
File file1 = ... // as before
File file2 = new File(file1.getCanonicalPath());
String path = file2.getParentFile().getCanonicalPath();