java canread_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值