canWrite()函数是Java中File类的一部分。该函数确定程序是否可以写入由抽象路径名表示的文件。如果存在抽象文件路径并且允许应用程序写入文件,则该函数返回true。
函数签名:
public boolean canWrite()
用法:
file.canWrite()
参数:此方法不接受任何参数。
返回值:该函数返回布尔值,该布尔值表示是否允许应用程序写入文件。
异常:如果对文件的写访问被拒绝,则此方法将引发安全性异常
以下示例程序旨在说明canWrite()函数的用法:
范例1:文件“F:\\program.txt”是可写的
// Java program to demonstrate
// canWrite() 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 written or not
if (f.canWrite())
System.out.println("Can be written");
else
System.out.println("Cannot be written");
}
}
输出:
Can be written
范例2:文件“F:\\program1.txt”是可写的
// Java program to demonstrate
// canWrite() 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 written or not
if (f.canWrite())
System.out.println("Can be written");
else
System.out.println("Cannot be written");
}
}
输出:
Cannot be written
注意:程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的路径。