2

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.

yasar
  • 13,158
  • 28
  • 95
  • 160
  • 4
    Can execute does not mean that it would execute, only that your permissions let you execute that file. In a way, that's like pointing to a mushroom, and ask "can I eat it?" The answer would be "yes" no matter what kind of mushroom you're pointing to, albeit for some mushrooms that answer would mean that you can eat it only once. – Sergey Kalinichenko Aug 09 '13 at 19:26

1 Answers1

3

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).

Commander Worf
  • 324
  • 1
  • 9
  • 2
    Note that suffix checking will only work for operating systems which care about file extensions (So not any of the *nix operating systems for example). – Aurand Aug 09 '13 at 19:35
  • Yeah, I should have noted this. For a Linux or *BSD system you will need some other test. – Commander Worf Aug 09 '13 at 19:36