The following is some simple code just to test the Files.walkFileTree()
method. However, the folder /etc/ssl/private
, which has these permissions (rwx--x---
), throws an exception, even when I thought I guarded it with an if statement (if (permissions.equals("rwx--x---")
).
What am I doing wrong? Thanks in advance.
public static void main (String []args) throws IOException, InterruptedException
{
Files.walkFileTree(Paths.get("/"), new WalkingTheThing2());
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
{
PosixFileAttributeView posixView = Files.getFileAttributeView(dir, PosixFileAttributeView.class);
PosixFileAttributes posixAttr = posixView.readAttributes();
String permissions =PosixFilePermissions.toString(posixAttr.permissions());
if (permissions.equals("rwx--x---"))
{
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
try{
System.out.println(file.getFileName()+" " +Files.size(file));
return FileVisitResult.CONTINUE;
}
catch(IOException io){return FileVisitResult.CONTINUE;}
}
The exception I get is: java.nio.file.AccessDeniedException: /etc/ssl/private
EDIT: Solved by overriding visitFileFailed
:
public FileVisitResult visitFileFailed(Path file, IOException io)
{
return FileVisitResult.SKIP_SUBTREE;
}
If you are traversing the whole directory System and there is a situation where you got some type of Exception like AccessDeniedException
and you want skip that file so that you could check the other file you need to override the visitFileFailed
and skip that file or directory.
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.err.printf("Visiting failed for %s\n", file);
return FileVisitResult.SKIP_SUBTREE;
}
This is the work around I have found when Walking through the directory system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With