Java – Check if file is executable

In this tutorial, we will learn about the Java File.canExecute() function, and learn how to use this function to check if a file is executable by the applicaiton, with the help of examples.

canExecute()

File.canExecute() returns true, if the application can execute the file denoted by this abstract pathname, else, it returns false.

The syntax of canExecute() function is

canExecute()

Returns

The function returns boolean value.

ADVERTISEMENT

Examples

1. Positive Scenario – The file is executable

In this example, we will take a text file with file path D:\sample.txt. Using canExecute() method, we will check if the file is executable or not.

Java Program

import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample.txt");
		if (f.canExecute()) {
			System.out.println("The file is executable."); 
		}
		else {
			System.out.println("The file is non-executable."); 
		}
	}
}

Output

The file is executable.

2. Negative Scenario – The file is not executable

In this example, we will create a File object with file path D:\sample_no_file.txt. There is no file with this path. Using canExecute() method, we will check if the file is executable or not.

Java Program

import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample_no_file.txt");
		if (f.canExecute()) {
			System.out.println("The file is executable."); 
		}
		else {
			System.out.println("The file is non-executable."); 
		}
	}
}

Output

The file is non-executable.

Conclusion

In this Java Tutorial, we learned how to check if the file is executable using File.canExecute() function, with the help of examples.