Chinaunix首页 | 论坛 | 博客
  • 博客访问: 105106
  • 博文数量: 31
  • 博客积分: 115
  • 博客等级: 民兵
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-19 16:02
文章分类
文章存档

2013年(1)

2012年(9)

2011年(21)

分类:

2011-12-29 09:09:02

原文地址:JAVA IO:修改文件权限 作者:tkchks

在java中,文件的权限对于不同的操作系统有不同的权限。 java 处理一些通用的权限。

检查文件是否允许:
  1. file.canExecute(); – return true, file is executable; false is not.
  2. file.canWrite(); – return true, file is writable; false is not.
  3. file.canRead(); – return true, file is readable; false is not.
设置文件权限:
  1. file.setExecutable(boolean); – true, allow execute operations; false to disallow it.
  2. file.setReadable(boolean); – true, allow read operations; false to disallow it.
  3. file.setWritable(boolean); – true, allow write operations; false to disallow it.
在*nix系统中,你可能需要配置更加明确的文件权限,如设置某个文件的权限为777.但是,java IO类没有相关方法。不过可以使用以下workaround:
  1. Runtime.getRuntime().exec("chmod 777 file");
查看和修改文件权限完整例子:

  1. package org.hnrsc.io;

  2. import java.io.File;
  3. import java.io.IOException;

  4. //
  5. public class JavaFileIO {

  6.     public static void main(String[] args) {
  7.         try {
  8.             String filename = "test1.txt";
  9.             String finalfile = "";
  10.             String workingDir = System.getProperty("user.dir");

  11.             
  12.             finalfile = workingDir + File.separator + filename;

  13.             System.out.println("Final filepath: " + finalfile);

  14.             File file = new File(finalfile);
  15.             if (file.createNewFile()) {
  16.                 System.out.println("File is created!");
  17.             } else {
  18.                 System.out.println("File already exists.");
  19.             }
  20.             if (file.exists()) {
  21.                 System.out.println("Is Execute allow : " + file.canExecute());
  22.                 System.out.println("Is Write allow : " + file.canWrite());
  23.                 System.out.println("Is Read allow : " + file.canRead());
  24.             }

  25.             file.setExecutable(false);
  26.             file.setReadable(false);
  27.             file.setWritable(false);

  28.             System.out.println("Is Execute allow : " + file.canExecute());
  29.             System.out.println("Is Write allow : " + file.canWrite());
  30.             System.out.println("Is Read allow : " + file.canRead());

  31.         } catch (IOException e) {
  32.             e.printStackTrace();
  33.         }
  34.     }
  35. }

本程序执行结果有点让人疑惑,为何设置以下属性为false后,只有writable变为false了?
  1.  file.setExecutable(false);
  2.  file.setReadable(false);
  3.  file.setWritable(false);

  1. Final filepath: N:\eclipse\workspace\JavaIO\test1.txt
  2. File already exists.
  3. Is Execute allow : true
  4. Is Write allow : true
  5. Is Read allow : true
  6. --------------------------
  7. Is Execute allow : true
  8. Is Write allow : false
  9. Is Read allow : true

阅读(2028) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~