문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top