Java中的文件 isExecutable() 方法及示例
Java.nio.file.Files的isExecutable()方法帮助我们检查文件是否可执行。此方法检查此路径上是否存在文件,如果存在,则Java虚拟机是否具有执行该文件的适当权限。检查对目录的访问时,语义可能会有所不同。
例如,在 UNIX 系统上,检查执行访问会检查Java虚拟机是否有权搜索目录以访问文件或子目录。所以我们可以说 isExecutable() 方法如果文件存在并且是可执行的则返回 true,或者如果以下情况返回 false:
- 文件不存在
- 执行访问将被拒绝,因为Java虚拟机没有足够的权限,
无法确定访问权限。
句法:
public static boolean isExecutable(Path path)
参数:此方法接受参数路径,该路径是要检查的文件的路径。
返回值:如果文件存在且可执行,则该方法返回true,如果出现以下情况,则返回false:
- 文件不存在
- 执行访问将被拒绝,因为Java虚拟机没有足够的权限,
无法确定访问权限。
异常:在默认提供程序的情况下,此方法将抛出SecurityException ,并且安装了安全管理器,调用 checkExec 以检查对文件的执行访问权限。
步行文件树。
下面的程序说明了 isExecutable(Path) 方法:
方案一:
// Java program to demonstrate
// Files.isExecutable() method
import java.io.IOException;
import java.nio.file.*;
public class GFG {
public static void main(String[] args)
{
// create an object of Path
Path path
= Paths.get(
"D:\\GIT_EWS_PROJECTS\\logger"
+ "\\src\\logger"
+ "\\GFG.java");
// check whether this file
// is executable or not
boolean result
= Files.isExecutable(path);
System.out.println("File " + path
+ " is Executable = "
+ result);
}
}
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Files_isExecutable()_method_in_Java_with_Examples_0.png)
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Files_isExecutable()_method_in_Java_with_Examples_0.png)
方案二:
// Java program to demonstrate
// Files.isExecutable() method
import java.io.IOException;
import java.nio.file.*;
public class GFG {
public static void main(String[] args)
{
// create object of Path for a file
// which did not exists.
Path path
= Paths.get(
"D:\\User Aman\\Documents"
+ "\\MobaXterm\\home"
+ "\\.ssh\\hostkeys\\file1.txt");
// check whether this file
// is executable or not
boolean result
= Files.isExecutable(path);
// as the file does not exist
// then answer should be false
System.out.println("File " + path
+ " is Executable = "
+ result);
}
}
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Files_isExecutable()_method_in_Java_with_Examples_1.png)
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Files_isExecutable()_method_in_Java_with_Examples_1.png)
参考资料: https: Java Java.nio.file.Path)