在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 keytool 不是内部命令或外部命令在 (win7下不能用的解决
  2. 如何查看无法导出的android数据库文件?
  3. Arcgis android 10.2安装方法
  4. Android studio 打不开官方虚拟机 100%成功解决方法
  5. 输入法软键盘搜索执行两次的解决方法
  6. 关于Android Studio里的Gradle文件
  7. android使用http协议上传文件
  8. Android 6.0 运行时权限检查分析
  9. Android 开发——'Android Pre Compiler'空指针问题的解决方法

随机推荐

  1. H5混合开发 js与java相互调用
  2. json形式的 Android(安卓)客户端与服务器
  3. Android的状态机模式StateMachine与State
  4. Android学习笔记-Android非布局activity
  5. android multicast 多播(组播)问题
  6. 2.1……Android中的单位简介
  7. Android(安卓)ListView pull up to refre
  8. android studio开发工具升级到3.6.0以后,a
  9. android正则表达式匹配中文正解
  10. Android Gradle 初识