Java - File canRead() 方法



描述

Java File canRead() 方法如果檔案可以透過其抽象名稱讀取,則返回 true。

宣告

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

public boolean canRead()

引數

返回值

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

異常

SecurityException - 如果 SecurityManager.checkRead(java.lang.String) 方法拒絕應用程式的讀取訪問許可權。

示例 1

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

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 readable
         boolean bool = f.canRead();

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

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

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

輸出

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

F:\test.txt is readable: true

示例 2

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

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 readable
         boolean bool = f.canRead();

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

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

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

輸出

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

F:\test1.txt is readable: false

示例 3

以下示例顯示了 Java File canRead() 方法的用法。我們建立了一個 File 引用。然後,我們使用給定位置不存在的檔案建立一個 File 物件。使用 canRead() 方法,我們獲取檔案的可讀狀態。然後使用 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 readable
         boolean bool = f.canRead();

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

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

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

輸出

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

F:\test2.txt is readable: false
java_file_class.htm
廣告

© . All rights reserved.