Java - File canWrite() 方法



描述

Java File canWrite() 方法返回 true,如果檔案可以透過其抽象名稱寫入。

宣告

以下是 java.io.File.canWrite() 方法的宣告:

public boolean canWrite()

引數

返回值

此方法返回布林值。如果路徑名存在並且應用程式允許執行該檔案,則返回 true。

異常

SecurityException − 如果 SecurityManager.checkWrite(java.lang.String) 方法拒絕對檔案的寫入訪問。

示例 1

以下示例演示了 Java File canWrite() 方法的用法。我們建立了一個 File 引用。然後,我們使用給定位置中存在的的檔案建立一個 File 物件。使用 canWrite() 方法,我們獲取檔案的可寫狀態。然後,使用 getAbsolutePath(),我們獲取檔案的絕對路徑。最後,我們列印檔名及其可寫狀態。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;      
         
      try {
         // create new file
         f = new File("F://test.txt");

         // true if the file is writable
         boolean bool = f.canWrite();

         // find the absolute path
         String path = f.getAbsolutePath(); 

         // prints
         System.out.println(path + " is writable: "+ bool);

      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果——假設我們在當前位置有一個 test.txt 檔案,並且它不可寫。

F:\test.txt is writable: true

示例 2

以下示例演示了 Java File canWrite() 方法的用法。我們建立了一個 File 引用。然後,我們使用一個不可寫(只讀)的檔案建立一個 File 物件。使用 canWrite() 方法,我們獲取檔案的可寫狀態。然後,使用 getAbsolutePath(),我們獲取檔案的絕對路徑。最後,我們列印檔名及其可寫狀態。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;      
         
      try {
         // create new file
         f = new File("F://test1.txt");

         // true if the file is writable
         boolean bool = f.canWrite();

         // find the absolute path
         String path = f.getAbsolutePath(); 

         // prints
         System.out.println(path + " is writable: "+ bool);

      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果——假設我們在給定位置有一個不可寫的 test2.txt 檔案。

F:\test1.txt is writable: false

示例 3

以下示例演示了 Java File canWrite() 方法的用法。我們建立了一個 File 引用。然後,我們使用給定位置中不存在的檔案建立一個 File 物件。使用 canWrite() 方法,我們獲取檔案的可寫狀態。然後,使用 getAbsolutePath(),我們獲取檔案的絕對路徑。最後,我們列印檔名及其可寫狀態。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;      
         
      try {
         // create new file
         f = new File("F://test2.txt");

         // true if the file is writable
         boolean bool = f.canWrite();

         // find the absolute path
         String path = f.getAbsolutePath(); 

         // prints
         System.out.println(path + " is writable: "+ bool);

      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果——假設我們在給定位置沒有 test2.txt 檔案,因此它不可寫。

F:\test2.txt is writable: false
java_file_class.htm
廣告
© . All rights reserved.