检查是否可以用Java读取文件

方法java.io.File.canRead()用于检查是否可以用Java读取文件。如果抽象路径名指定的文件可以被应用程序读取,则此方法返回true,否则返回false。

演示此的程序如下所示-

示例

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("The file can be read? " + file.canRead());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

上面程序的输出如下-

输出结果

The file can be read? true

现在让我们了解上面的程序。

方法java.io.File.canRead()用于检查是否可以读取文件,并打印该方法返回的布尔值。证明这一点的代码片段如下-

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("The file can be read? " + file.canRead());
} catch(Exception e) {
   e.printStackTrace();
}