Java File canExecute() method with examples

November 29, 2019 No comments Java IO Example canExecute

1. Introduction

The canExecute() method tests if application can execute provided file. You shouldn't be relying on this method. Sometimes it will return true even though the file does not have permissions to execute, also JVM could be started with special privileges that allow it to execute files not marked executable.

2. Method signature

public boolean canExecute()

Parameters:

  • method does not take any parameter

Returns

  • true - if file is executeable and application can execute it

Throws

  • SecurityException - application does not have permission to the file

3. Examples

3.1. Check if file /tmp/script.sh can be executed

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/script.sh");
            boolean canExecute = f.canExecute();

            if (canExecute) {
                System.out.println("Application can execute the file");
            } else {
                System.out.println("Application cannot execute the file");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output in a scenario when script.sh is executable in OS (used chmod +x filename to allow executable permissions):

Application can execute the file

4. Conclusion

In this article, we showcased how we could use File.canExecute() method to check if the given file can be executed by the application. Note that you shouldn't trust 100% of what this method returns, because specific parameters of a virtual Java machine will make applications able to execute a file that is not marked as executable.

{{ message }}

{{ 'Comments are closed.' | trans }}