在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);

该方法调用系统命令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屏幕元素层次结构
  2. Android之SharedPreferences简介及使用说明
  3. ChkBugReport工具 for Android(安卓)1
  4. Android根据文件路径使用File类获取文件相关信息
  5. Android本地数据存储之Sharedpreference
  6. android keytool 不是内部命令或外部命令在 (win7下不能用的解决
  7. Android中视频播放以及解码
  8. 如何查看无法导出的android数据库文件?
  9. Android(安卓)Studio 常用快捷键

随机推荐

  1. Android 在界面中显示以及输入文本信息 T
  2. android ListView控件 去上下滑动阴影 选
  3. android udp通信
  4. 【android】关于退出时关闭“后台”显示
  5. Ubuntu 系统上编译Android 系统
  6. [置顶] Android进程间通信AIDL的使用分析
  7. Android音视频处理之MediaExtractor
  8. 求助: Android 加载 webview, 点击webvie
  9. android 布局文件属性说明
  10. Android imageView 属性知识