Java文件类boolean canRead()方法(带示例)

文件类 boolean canRead()

  • 包java.io.File.canRead()中提供了此方法。

  • 此方法用于读取文件,并且文件由抽象文件路径表示。

  • 此方法的返回类型为Boolean,即返回true或false,如果为true表示可以读取文件路径所表示的文件,或者换句话说,文件已经存在要读取,则返回false表示文件不存在或不允许读书。

  • 如果未授予文件读取访问权限,则此方法可能会引发异常(即Security Exception)。

语法:

    boolean canRead(){
    }

参数:

我们不会在File方法中将任何对象作为参数传递。

返回值:

此方法的返回类型为Boolean,即如果文件已存在并且允许读取文件(由抽象文件路径表示),则返回true,否则返回false。

Java程序演示canRead()方法示例

//导入File类,因为我们将使用File类方法
import java.io.File;

//导入Exception类,因为 
//使用文件时可能会引发异常
import java.lang.Exception;

public class ReadFile {
    public static void main(String[] args) {
        try {
            //指定文件的路径,我们使用双斜杠 
            //为Windows转义'\'字符序列 
             
            File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
            File file2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\java.txt");

            //通过使用canRead()允许读取文件 
            //如果文件已经存在并且返回true- 
            //如果文件可读,则返回false。
            if (file1.canRead())
                System.out.println("This file " + file1.getName() + " " + "is readable");
            else
                System.out.println("This file " + file1.getName() + " " + "is not readable");

            //通过使用canRead()不允许读取文件 
            //因为此文件尚不存在,并且返回false。
            if (file2.canRead())
                System.out.println("This file " + file2.getName() + " " + "is readable");
            else
                System.out.println("This file " + file2.getName() + " " + "is not readable");
        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

输出结果

D:\Programs>javac ReadFile.java
D:\Programs>java ReadFile

This file C:\Users\computer clinic\OneDrive\Articles\myjava.txt is not readable
This file C:\Users\computer clinic\OneDrive\Articles\java.txt is not readable