在Android中通过Java修改文件权限

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

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

 1. 用openFileOutput方法:

 

[java] view plaincopy

  1. FileOutputStream fos;    
  2. fos = openFileOutput("filename", MODE_WORLD_READABLE);   

FileOutputStream android.content.ContextWrapper .openFileOutput(String name, 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 plaincopy

  1. Runtime.getRuntime().exec("chmod 644 " + filename);  

 

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

 

[java] view plaincopy

  1. Process p = Runtime.getRuntime().exec("chmod 644 " + filename);    
  2. int status = p.waitFor();    
  3. if (status == 0) {    
  4.     //chmod succeed    
  5. else {    
  6.     //chmod failed    
  7. }    

 

Android在apk内部,即通过java代码来进行修改系统文件或者修改系统设置等等,这样需要获取系统权限。  

通过直接配置apk运行在System进程内

 1. 在应用程序的AndroidManifest.xml中的manifest节点中加入android:sharedUserId="android.uid.system"这个属性。
  2. 修改Android.mk文件,加入LOCAL_CERTIFICATE := platform这一行
  3. 使用mm命令来编译,生成的apk就有系统权限了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值