java中怎么设置文件权限

java中怎么设置文件权限,第1张

import java.io.IOException/××只能给当前用户赋予对该文件权限,调用createNewFile()方法默认的权限是644.

×/public class FilePermission{public static void main( String[] args ){try {File file = new File("/home/test3.txt")

if (file.createNewFile()){

System.out.println("File is created!")

//Runtime.getRuntime().exec("chmod 777 /home/test3.txt")

file.setExecutable(true)//设置可执行权限

file.setReadable(true)//设置可读权限

file.setWritable(true)//设置可写权限

System.out.println("is execute allow : " + file.canExecute())

System.out.println("is read allow : " + file.canRead())

System.out.println("is write allow : " + file.canWrite())}else{System.out.println("File already exists.")}

在Java中,文件权限是非常具体的 *** 作系统:* nix中,NTFS(Windows)及FAT/FAT32,都有着别样的文件权限。 Java提供了一些通用的文件权限来处理它。

检查文件权限允许:

1.file.canExecute()– 返回true,文件是可执行的,false 则不是。

2.file.canWrite()– 返回true,文件是可写的,false 则不是。

3.file.canRead()– 返回true,文件是可读的,false 则不是。

设置文件权限:

1.file.setExecutable(boolean)– true允许执行 *** 作false则是禁止它。

2.file.setReadable(boolean)– true允许读 *** 作false则是禁止它。

3.file.setWritable(boolean)– true允许写 *** 作false则是禁止它。

在* nix的系统中,可能需要配置有关文件权限的详细指定,例如设置777权限的文件或目录,但是,Java的IO类没有现成的方法,但你可以使用下面的解决方法:

Runtime.getRuntime().exec("chmod 777 file")文件权限的例子

import java.io.File

import java.io.IOException

×只能给当前用户赋予对该文件的权限,调用createNewFile()方法默认的权限是644.

×/

public class FilePermission

{

public static void main( String[] args )

{

try {

File file = new File("/home/test3.txt")

if (file.createNewFile()){

System.out.println("File is created!")

//Runtime.getRuntime().exec("chmod 777 /home/test3.txt")

file.setExecutable(true)//设置可执行权限

file.setReadable(true)//设置可读权限

file.setWritable(true)//设置可写权限

System.out.println("is execute allow : " + file.canExecute())

System.out.println("is read allow : " + file.canRead())

System.out.println("is write allow : " + file.canWrite())

}else{

System.out.println("File already exists.")

}

} catch (IOException e) {

e.printStackTrace()

}

}

额,是更改文件的权限吗?希望能帮到你chmod("777",文件路径)即可[mw_shl_code=java,true]public static void chmod(String permission, String path) { try { String command = "chmod " + permission + " " + pathRuntime runtime = Runtime.getRuntime()runtime.exec(command)} catch (IOException e) { e.printStackTrace()} }[/mw_shl_code] 查看更多答案>>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/bake/11945402.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存