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

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

1. 用openFileOutput方法:

[java] view plain copy
  1. FileOutputStreamfos;
  2. fos=openFileOutput("filename",MODE_WORLD_READABLE);

FileOutputStreamandroid.content.ContextWrapper.openFileOutput(Stringname, int mode) throwsFileNotFoundException

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()

[c-sharp] view plain copy
  1. Runtime.getRuntime().exec("chmod644"+filename);

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

[java] view plain copy
  1. Processp=Runtime.getRuntime().exec("chmod644"+filename);
  2. intstatus=p.waitFor();
  3. if(status==0){
  4. //chmodsucceed
  5. }else{
  6. //chmodfailed
  7. }

更多相关文章

  1. Android-缓存数据保存-通用方法
  2. Android 中 ListView Adapter getView 被多次调用问题 解决方法
  3. Android开发便签9:在android资源文件中定义字符串数组
  4. java/android 统计文件夹大小及删除文件夹下所有文件和路径
  5. Android监听来电和去电的实现方法
  6. Android 屏幕的旋转 onConfigurationChanged方法
  7. 查看android里的数据库的内容的方法
  8. Android:使用SAX或者DOM或者pull操作XML文件
  9. android系统中运行jar文件

随机推荐

  1. Android编译过程详解(二)
  2. Android(安卓)- 修改最小SDK版本(minSdkV
  3. Android属性之build.prop生成过程分析
  4. Android(安卓)模仿QQ风格的 UI
  5. android 研究笔记
  6. 为什么Android没有iOS顺滑zz
  7. 关于android应用程序的入口
  8. android在list view中如何action的实现
  9. [Android] 获取Android设备的唯一识别码|
  10. 大话企业级android读书笔记(二)