Java中的文件权限

Java提供了许多方法调用来检查和更改文件的权限,例如只读文件可以更改为具有写入权限。当用户想要限制文件上允许的操作时,需要更改文件权限。例如,文件权限可以从写更改为只读,因为用户不再想要编辑文件。

null

正在检查当前文件权限

文件可以是以下允许权限的任意组合,这些权限由以下表格格式的方法描述/

方法 执行的动作
可执行的 退换商品 当且仅当抽象路径名存在且允许应用程序执行该文件时,为true
canRead() 测试应用程序是否可以读取由该抽象路径名表示的文件
canWrite() 当且仅当文件系统实际包含由该抽象路径名表示的文件且允许应用程序写入该文件时,返回true;否则就错了

实施: 文件可以可读写,但不能执行。下面是一个Java程序,用于获取与文件关联的当前权限。

例子:

JAVA

// Java Program to Check the Current File Permissions
// Importing required classes
import java.io.*;
// Main class
public class Test {
// Main driver method
public static void main(String[] args)
{
// Creating a file by
// creating object of Fiel class
File file
= new File( "C:\Users\Mayank\Desktop\1.txt" );
// Checking if the file exists
// using exists() method of File class
boolean exists = file.exists();
if (exists == true ) {
// Printing the permissions associated
// with the file
System.out.println( "Executable: "
+ file.canExecute());
System.out.println( "Readable: "
+ file.canRead());
System.out.println( "Writable: "
+ file.canWrite());
}
// If we enter else it means
// file does not exists
else {
System.out.println( "File not found." );
}
}
}


输出:

图片[1]-Java中的文件权限-yiteyi-C++库

更改文件权限

Java文件可以具有以下权限的任意组合:

  • 可执行文件
  • 可读的
  • 可写

以下是更改与文件关联的权限的方法,如以下表格格式所示:

方法 执行的动作
setExecutable() 设置所有者对此抽象路径名的执行权限
setReadable() 设置所有者对此抽象路径名的读取权限
setWritable() 设置所有者对此抽象路径名的写入权限

注:

  • setReadable()操作 如果用户无权更改此抽象路径名的访问权限,则将失败。如果readable为false,并且底层文件系统未实现读取权限,则操作将失败。
  • 如果用户无权更改此抽象路径名的访问权限,setWritable()操作将失败。

例子:

JAVA

// Java Program to Change File Permissions
// Importing required classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a new file by
// creating object of File class where
// local directory is passed as in argumenyt
File file
= new File( "C:\Users\Mayank\Desktop\1.txt" );
// Checking if file exists
boolean exists = file.exists();
if (exists == true ) {
// Changing the file permissions
file.setExecutable( true );
file.setReadable( true );
file.setWritable( false );
System.out.println( "File permissions changed." );
// Printing the permissions associated with the
// file currently
System.out.println( "Executable: "
+ file.canExecute());
System.out.println( "Readable: "
+ file.canRead());
System.out.println( "Writable: "
+ file.canWrite());
}
// If we reach here, file is not found
else {
System.out.println( "File not found" );
}
}
}


输出:

图片[2]-Java中的文件权限-yiteyi-C++库

本文由 马扬克·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享