博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux 下 java 修改文件权限
阅读量:4216 次
发布时间:2019-05-26

本文共 1935 字,大约阅读时间需要 6 分钟。

Java 修改文件权限这个应该是老生常谈的功能,但是最近发现以前写的代码有一点点安全隐患,所以把代码改成NIO的方式,下面会介绍2种修改文件,文件夹权限的方法。

使用File类 

这个方式是以前最常见的方式,但是这个方式有点缺点在LINUX或者UNIX系统下,需要显示的指定权限为440,770等就显得不是那么好用了。

File dirFile = new File(dirPath);dirFile.setReadable(true, false);dirFile.setExecutable(true, false);dirFile.setWritable(true, false);
  • 1
  • 2
  • 3
  • 4

因此我们通常会采用一些workaround的方式修改文件夹权限,必须我需要在LINUX上设置权限为770

Runtime runtime = getRuntime();String command = "chmod 770 " + dirPath;try {    Process process = runtime.exec(command);    process.waitFor();    int existValue = process.exitValue();    if(existValue != 0){        logger.log(Level.SEVERE, "Change file permission failed.");        }     } catch (Exception e) {        logger.log(Level.SEVERE, "Command execute failed.", e);     }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这种方式会有一个问题,当dirPath中包含空格或者分号的时候,不仅仅对功能有影响,对安全也是有隐患的。 

情况1: dirPath = /home/a aa.txt 
在LINUX系统中执行的命令是 chmod 770 /home/a aa.txt , 系统会认为修改/home/a 和aa.txt 的文件权限为770,修改文件权限失败 
情况2: 当dirPath = /home/aaa.txt;rm test.txt 
这时在LINUX系统中会执行2条指令:

chmod 770 /home/omc/aaa.txtrm test.txt
  • 1
  • 2

这时就会出现安全隐患。

NIO方式

private void changeFolderPermission(File dirFile) throws IOException {    Set
perms = new HashSet
(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); try { Path path = Paths.get(dirFile.getAbsolutePath()); Files.setPosixFilePermissions(path, perms); } catch (Exception e) { logger.log(Level.SEVERE, "Change folder " + dirFile.getAbsolutePath() + " permission failed.", e); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

从API 查询知道,NIO的这种方式原生支持LINUX和UNIX低层系统,但测试发现在Windows系统下面不区分文件所有者和其它似乎没有效果,这个和实用File是一致的。从底层代码发现,还是使用的File类 

另外可能会抛出UnsupportedOperationException IOException SecurityException

转载地址:http://nhnmi.baihongyu.com/

你可能感兴趣的文章
【屌丝程序的口才逆袭演讲稿50篇】第十二篇:世界上最快的捷径【张振华.Jack】
查看>>
Android中Java代码和XML布局效率问题
查看>>
android TextView属性大全(转)
查看>>
Conclusion for Resource Management
查看>>
Conclusion for Constructors,Destructors,and Assignment Operators
查看>>
Conclusion for Accustoming Yourself to C++
查看>>
面试题1:赋值运算函数(offer)
查看>>
面试题15:在O(1)时间删除链表结点
查看>>
面试题16:调整数组顺序使奇数位于偶数前面
查看>>
面试题17:链表中倒数第k个结点(offer)
查看>>
面试题18:反转链表
查看>>
面试题19:合并两个排序的链表(offer)
查看>>
QT之局域网聊天实现
查看>>
poco之文件系统
查看>>
QT实现记录上一次用户名和密码功能
查看>>
QT通过按钮browse文件夹
查看>>
GetUdpTable获得UDP端口使用信息
查看>>
QtCharts动态的显示折线图
查看>>
生成Send Report的rtcp包接口
查看>>
docker使用
查看>>