Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working around access denied in a FileWalking Tree in Java7

Tags:

java

io

nio

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;
}
like image 687
Rollerball Avatar asked Aug 12 '13 21:08

Rollerball


1 Answers

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.

like image 61
Root Avatar answered Nov 16 '22 05:11

Root