Question

I am using this code to test it;

public class CanExecuteTest {
    public static void main (String[] args) {
        File currentDir = new File(System.getProperty("user.dir"));
        traverse(currentDir);
    }

    public static void traverse(File dir) {
        String[] filesAndDirs = dir.list();
        for (String fileOrDir : filesAndDirs) {
            File f = new File(dir, fileOrDir);
            if (f.isDirectory()) {
                traverse(f);
            } else {
                System.out.print(f);
                if (f.canExecute()) {
                    System.out.println(" can execute");
                } else {
                    System.out.println(" cannot execute");
                }
            }
        }
    }
}

This outputs that every file is an executable file. Am I doing something wrong here, or is this a java bug? I am on windows 7, netbeans 7.3.1 and java 7.

Was it helpful?

Solution

canExecute() doesn't test for executability, it tests whether the current program (i.e. yours) is permitted to execute it. For example, if you changed the permissions of one of the files to 000 (no read, write, or execute by any user), canExecute() would probably return false as the JVM would not have permission to execute (or read) the file.

If you want to check for executable files, you could probably create a method that parses files for their suffix and returns true when it finds .exe (or .app on OS X).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top