文件类boolean canRead() (File Class boolean canRead())
This method is available in package java.io.File.canRead().
软件包java.io.File.canRead()中提供了此方法。
This method is used to read the file and the file is represented by the abstract filepath.
此方法用于读取文件,并且文件由抽象文件路径表示。
The return type of this method is Boolean i.e. it returns true or false if true that means file can be read which is represented by the filepath or in other words file already exists to read and returns false that means the file does not exist or not allowed to read.
此方法的返回类型为Boolean,即返回true或false,如果为true表示可以读取文件路径表示的文件,或者换句话说,文件已经存在要读取,则返回false表示文件不存在或不允许阅读。
This method may raise an exception( i.e. Security Exception) if the read access is not given to the file.
如果未授予文件读取访问权限,则此方法可能会引发异常(即Security Exception)。
Syntax:
句法:
boolean canRead(){
}
Parameter(s):
参数:
We don't pass any object as a parameter in the method of the File.
我们不会在File方法中将任何对象作为参数传递。
Return value:
返回值:
The return type of this method is Boolean i.e. it returns true if the file already exists and allowed to read the file which is denoted by the abstract file path returns false otherwise.
此方法的返回类型为Boolean,即如果文件已存在并且允许读取文件(由抽象文件路径表示),则返回true,否则返回false。
Java程序演示canRead()方法的示例 (Java program to demonstrate example of canRead() method)
// import the File class because we will use File class methods
import java.io.File;
// import the Exception class because
// it may raise an exception when working with files
import java.lang.Exception;
public class ReadFile {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes
// to escape '\' character sequence for windows otherwise
// it will be considerable as url.
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
File file2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\java.txt");
// By using canRead() is allowed to read the file
// if file is already exists and it returns true
// if file is readable else false.
if (file1.canRead())
System.out.println("This file " + file1.getName() + " " + "is readable");
else
System.out.println("This file " + file1.getName() + " " + "is not readable");
// By using canRead() is not allowed to read the file
// because this file is not already exists and it returns 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();
}
}
}
Output
输出量
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
翻译自: https://www.includehelp.com/java/file-class-boolean-canread-method-with-example.aspx