java file setreadonly,Java File setReadOnly()用法及代碼示例

setReadOnly()方法是File類的一部分。 setReadOnly()函數標記指定的文件或目錄,以便僅允許對該文件或目錄進行讀取操作。

函數簽名:

public boolean setReadOnly()

用法:

file.setReadOnly()

參數:該功能不需要任何參數。

返回值:該函數返回布爾數據類型。如果File對象可以設置為Read Only,則該函數返回true,否則返回false。

異常:如果該方法不允許對該文件進行寫訪問,則此方法將引發SecurityException

下麵的程序將說明setReadOnly()函數的用法:

範例1:將現有文件“F:\program.txt”設置為隻讀

// Java program to demonstrate

// the use of File.setReadOnly() method

import java.io.*;

public class GFG {

public static void main(String args[])

{

// create an abstract pathname (File object)

File f = new File("F:\\program.txt");

// check if the file object

// can be set as Read Only or not

if (f.setReadOnly()) {

// display that the file object

// is set as Read Only or not

System.out.println("File set as Read Only");

}

else {

// display that the file object

// cannot be set as Read Only or not

System.out.println("File cannot be set"

+ " as Read Only");

}

}

}

輸出:

File set as Read Only

範例2:將不存在的文件“F:\program1.txt”設置為隻讀

// Java program to demonstrate

// the use of File.setReadOnly() method

import java.io.*;

public class GFG {

public static void main(String args[])

{

// create an abstract pathname (File object)

File f = new File("F:\\program1.txt");

// check if the file object

// can be set as Read Only or not

if (f.setReadOnly()) {

// display that the file object

// is set as Read Only or not

System.out.println("File set as Read Only");

}

else {

// display that the file object

// cannot be set as Read Only or not

System.out.println("File cannot be set"

+ " as Read Only");

}

}

}

輸出:

File cannot be set as Read Only

這些程序可能無法在在線IDE中運行。請使用離線IDE並設置文件的路徑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值