在LINUX下每个文件都有一个权限的属性 ,那么在Android中怎么用java改变某个文件的权限呢?

Android中有两种方法可以改变文件的权限 

1. 用openFileOutput方法:

view plaincopy to clipboardprint?
01.FileOutputStream fos;
02.fos = openFileOutput("filename", MODE_WORLD_READABLE);
FileOutputStream fos;
fos = openFileOutput("filename", MODE_WORLD_READABLE);

FileOutputStream android.content.ContextWrapper .openFileOutput(String name, int mode) throws FileNotFoundException

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.

可用的mode 参数如下:

/**
* File creation mode: the default mode, where the created file can only
* be accessed by the calling application (or all applications sharing the
* same user ID).
* @see #MODE_WORLD_READABLE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_PRIVATE = 0x0000;
/**
* File creation mode: allow all other applications to have read access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_WORLD_READABLE = 0x0001;
/**
* File creation mode: allow all other applications to have write access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_READABLE
*/
public static final int MODE_WORLD_WRITEABLE = 0x0002;
/**
* File creation mode: for use with {@link #openFileOutput}, if the file
* already exists then write data to the end of the existing file
* instead of erasing it.
* @see #openFileOutput
*/
public static final int MODE_APPEND = 0x8000;

其实该方法最终还是调用了系统的chmod来实现的改变文件权限的功能。

但是该方法有局限性,他创建的文件只能位于该程序的私有目录下,即/data/data/app-package/files/

2. 用Runtime.getRuntime().exec()

view plaincopy to clipboardprint?
01.Runtime.getRuntime().exec("chmod 644 " + filename);
Runtime.getRuntime().exec("chmod 644 " + filename);

在Unix和Linux的各种操作系统下,每个文件(文件夹也被看作是文件)都按读、写、运行设定权限。

读、写、运行三项权限可以用数字表示,就是r=4,w=2,x=1。所以,rw-r--r--用数字表示成644。
反过来说777就是rwxrwxrwx,意思是该登录用户(可以用命令id查看)、他所在的组和其他人都有最高权限。
Android中可用通过adb shell 方法修改文件的权限,有时候我们需要在代码中实现改功能,

该方法调用系统命令chmod来改变文件的权限,为了能判断命令的返回值,最好写成:

view plaincopy to clipboardprint?
01.Process p = Runtime.getRuntime().exec("chmod 644 " + filename);
02.int status = p.waitFor();
03.if (status == 0) {
04.    //chmod succeed
05.} else {
06.    //chmod failed
07.}

更多相关文章

  1. Android(安卓)Studio系列-签名打包
  2. Android(安卓)开发中使用 SQLite 数据库
  3. AVD(android virtual device)路径设置
  4. Android心得3.2--用SAX解析器解析xml文件内容
  5. Android(安卓)Test 基础知识
  6. 浅谈Java中Collections.sort对List排序的两种方法
  7. NPM 和webpack 的基础使用
  8. Python list sort方法的具体使用
  9. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程

随机推荐

  1. android保存手势操作到文件&读取识别手势
  2. Android之SlidingDrawer抽屉效果
  3. 在 Ubuntu 下使用 Android NDK r4b 编译
  4. 真机上运行monkeyrunner python脚本踩坑
  5. android开发环境建立以及开发工具的使用-
  6. Android Utils
  7. Android 中的WiFi学习笔记——经典
  8. Android JNI 使用其它语言
  9. Android activity 生命周期(一)
  10. 最新下载 android 源码方法