Java File setExecutable()方法及示例

Java File setExecutable()方法及示例

setExecutable() 方法是File类的一部分。该函数设置所有者或所有人执行抽象路径名的权限。

该函数是一个重载函数,一个函数需要两个参数,另一个只有一个。

函数签名

public boolean setExecutable(boolean a, boolean b)
public boolean setExecutable(boolean a)

函数语法

file.setExecutable(boolean a, boolean b)
file.setExecutable(boolean a)

参数: 该函数是一个重载函数

对于第一个重载

  • 如果第一个参数是真值,那么允许执行抽象路径名,否则不允许执行该文件。
  • 如果第二个参数是真值,那么执行权限只适用于所有者,否则适用于所有人。

对于第二个重载

  • 如果一个真值作为参数被传递,那么它允许执行抽象路径名,否则不允许执行文件。

返回值: 该函数返回布尔值,即操作是否成功。

异常: 如果该函数不允许对文件进行写操作,该方法会抛出安全异常。

下面的程序将说明setExecutable()函数的使用情况

例1: 我们将尝试改变f:目录下一个现有文件的所有者的setExecutable权限。

// Java program to demonstrate the
// use of setExecutable() function
  
import java.io.*;
  
public class solution {
    public static void main(String args[])
    {
  
        // try-catch block to handle exceptions
        try {
  
            // Create a file object
            File f = new File("f:\\program.txt");
  
            // Check if the Executable permission
            // can be set to new value
            if (f.setExecutable(true)) {
  
                // Display that the Executable permission
                // is be set to new value
                System.out.println("Executable permission"
                                   + " is set");
            }
            else {
  
                // Display that the Executable permission
                // cannot be set to new value
                System.out.println("Executable permission"
                                   + " cannot be set");
            }
        }
        catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

输出

Executable permission is set

例2: 我们将尝试改变f:目录下每个现有文件的setExecutable权限。

// Java program to demonstrate the
// use of setExecutable() function
  
import java.io.*;
  
public class solution {
    public static void main(String args[])
    {
  
        // try-catch block to handle exceptions
        try {
  
            // Create a file object
            File f = new File("f:\\program.txt");
  
            // Check if the Executable permission
            // can be set to new value
            if (f.setExecutable(true, false)) {
  
                // Display that the Executable permission
                // is be set to new value
                System.out.println("Executable permission"
                                   + " is set");
            }
            else {
  
                // Display that the Executable permission
                // cannot be set to new value
                System.out.println("Executable permission"
                                   + " cannot be set");
            }
        }
        catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

输出

Executable permission is set

这些程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的父文件

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程