當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java File canWrite()用法及代碼示例

canWrite()函數是Java中File類的一部分。該函數確定程序是否可以寫入由抽象路徑名表示的文件。如果存在抽象文件路徑並且允許應用程序寫入文件,則該函數返回true。

函數簽名:

public boolean canWrite()

用法:


file.canWrite()

參數:此方法不接受任何參數。

返回值:該函數返回布爾值,該布爾值表示是否允許應用程序寫入文件。

異常:如果對文件的寫訪問被拒絕,則此方法將引發安全性異常

以下示例程序旨在說明canWrite()函數的用法:

範例1:文件“F:\\program.txt”是可寫的

// Java program to demonstrate 
// canWrite() method of File Class 
  
import java.io.*; 
  
public class solution { 
    public static void main(String args[]) 
    { 
  
        // Get the file 
        File f = new File("F:\\program.txt"); 
  
        // Check if the specified file 
        // can be written or not 
        if (f.canWrite()) 
            System.out.println("Can be written"); 
        else
            System.out.println("Cannot be written"); 
    } 
}

輸出:

Can be written

範例2:文件“F:\\program1.txt”是可寫的

// Java program to demonstrate 
// canWrite() method of File Class 
  
import java.io.*; 
  
public class solution { 
    public static void main(String args[]) 
    { 
  
        // Get the file 
        File f = new File("F:\\program1.txt"); 
  
        // Check if the specified file 
        // can be written or not 
        if (f.canWrite()) 
            System.out.println("Can be written"); 
        else
            System.out.println("Cannot be written"); 
    } 
}

輸出:

Cannot be written

注意:程序可能無法在在線IDE中運行。請使用離線IDE並設置文件的路徑。



相關用法


注:本文由純淨天空篩選整理自andrew1234大神的英文原創作品 File canWrite() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。