Java File canWrite()方法及示例

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

Java File canWrite()方法及示例

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并设置文件的路径

相关推荐