Reputation: 710
I'm messing around with Java NIO and for some reason I can't get Files.isHidden() to return the correct boolean value. The program just checks to see if the directory is hidden then if it is hidden will make it visible and if it is not hidden it will make it hidden. This is what I have:
Path start = FileSystems.getDefault().getPath("E:/Documents/someDirectory");
try {
if (Files.isHidden(start)){
System.out.println("Dir is hidden.");
Files.setAttribute(start, "dos:hidden", false);
} else {
System.out.println("Dir is not hidden. Hiding.");
Files.setAttribute(start, "dos:hidden", true);
}
} catch (IOException e) {
e.printStackTrace();
}
It keeps returning false and hiding the directory despite the directory being hidden. The following code works fine using the old File class w/ the Path class.
Path start = FileSystems.getDefault().getPath("E:/Documents/someDirectory");
File file = new File("E:/Documents/someDirectory");
try {
if (file.isHidden()){
System.out.println("Dir is hidden.");
Files.setAttribute(start, "dos:hidden", false);
} else {
System.out.println("Dir is not hidden. Hiding.");
Files.setAttribute(start, "dos:hidden", true);
}
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1
Views: 791
Reputation: 298469
As already pointed out in the comments, the documentation of Files.isHidden
states:
The exact definition of hidden is platform or provider dependent. […] On Windows a file is considered hidden if it isn't a directory and the DOS hidden attribute is set.
While the last cited sentence already explains while it doesn’t return the expected value for a directory on Windows, I want to emphasize the first sentence. You are using a method burdened with a platform/provider specific semantics, while all you want to do, is to toggle a particular, platform specific flag.
In that case, you should just do exactly that, which also elides the conditionals of your code:
Path start=Paths.get("E:/Documents/someDirectory");
boolean isHidden=(Boolean)Files.getAttribute(start, "dos:hidden");
System.out.println("Dir is "+(isHidden? "hidden. Showing.": "not hidden. Hiding"));
Files.setAttribute(start, "dos:hidden", !isHidden);
Note also the convenience method Paths.get(…)
for FileSystems.getDefault().getPath(…)
.
Upvotes: 2