当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java File setWritable()用法及代码示例


setWritable()方法是File类的一部分。该函数设置所有者或所有人的许可,以写入抽象路径名。该函数是重载函数。一个函数需要两个参数,另一个仅需要一个。

函数签名:

public boolean setWritable(boolean a, boolean b)
public boolean setWritable(boolean a)

函数语法:


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

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

  • 对于第一次过载:
    • 如果将真实值作为第一个参数传递,则可以写入抽象路径名,否则不允许写入文件。
    • 如果将真实值作为第二个参数传递,则“写入”权限仅适用于所有者,否则适用于所有人

返回值:该函数返回一个布尔值,该值指示操作是否成功。

异常:如果不允许该函数对该文件进行写访问,则此方法将引发Security Exception。

下面的程序将说明setWritable()函数的用法

范例1:我们将尝试更改f:目录中现有文件的所有者的setWritable权限。

// Java program to demonstrate the 
// use of setWritable() 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 Writable permission 
            // can be set to new value 
            if (f.setWritable(true)) { 
  
                // Display that the Writable permission 
                // is be set to new value 
                System.out.println("Writable permission is set"); 
            } 
            else { 
  
                // Display that the Writable permission 
                // cannot be set to new value 
                System.out.println("Writable permission cannot be set"); 
            } 
        } 
        catch (Exception e) { 
            System.err.println(e.getMessage()); 
        } 
    } 
}

输出:

Writable permission is set

范例2:我们将尝试更改f:目录中每个现有文件的setWritable权限。

// Java program to demonstrate the 
// use of setWritable() 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 Writable permission 
            // can be set to new value 
            if (f.setWritable(true, false)) { 
  
                // Display that the Writable permission 
                // is be set to new value 
                System.out.println("Writable permission"
                                   + " is set"); 
            } 
            else { 
  
                // Display that the Writable permission 
                // cannot be set to new value 
                System.out.println("Writable permission"
                                   + " cannot be set"); 
            } 
        } 
        catch (Exception e) { 
            System.err.println(e.getMessage()); 
        } 
    } 
}

输出:

Writable permission is set

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



相关用法


注:本文由纯净天空筛选整理自andrew1234大神的英文原创作品 File setWritable() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。