Java File canRead()方法及示例

来源:这里教程网 时间:2026-02-17 20:53:32 作者:

Java File canRead()方法及示例

canRead() 函数是Java中文件类的一部分。这个函数决定了程序是否可以读取抽象路径名所表示的文件。如果抽象文件路径存在,并且应用程序被允许读取该文件,则该函数返回true。

函数签名

public boolean canRead()

语法

file.canRead()

参数: 该方法不接受任何参数。

返回值: 该函数返回一个 布尔值 ,代表应用程序是否被允许读取该文件。

异常: 如果对文件的读取权限被拒绝,该方法会抛出 安全异常

下面的程序说明了canRead()函数的使用。

例1: 文件 “F:\program.txt “是可读的

// Java program to demonstrate// canRead() 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 read or not        if (f.canRead())            System.out.println("Can be Read");        else            System.out.println("Cannot be Read");    }}

输出

Can be Read

例2: 文件 “F:\program1.txt “不可读

// Java program to demonstrate// canRead() 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 read or not        if (f.canRead())            System.out.println("Can be Read");        else            System.out.println("Cannot be Read");    }}

输出

Cannot be Read

注意: 这些程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的路径。

相关推荐