码迷,mamicode.com
首页 > 移动开发 > 详细

在Android java代码中如何改变文件的权限

时间:2014-05-26 16:21:52      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:android   style   c   class   blog   code   

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

 

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

 1. 用openFileOutput方法:

bubuko.com,布布扣
FileOutputStream fos;  
fos = openFileOutput("filename", MODE_WORLD_READABLE); 
bubuko.com,布布扣

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

bubuko.com,布布扣
Runtime.getRuntime().exec("chmod 644 " + filename);
bubuko.com,布布扣

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

bubuko.com,布布扣
Process p = Runtime.getRuntime().exec("chmod 644 " + filename);  
int status = p.waitFor();  
if (status == 0) {  
    //chmod succeed  
} else {  
    //chmod failed  
}  
bubuko.com,布布扣

 

在Android java代码中如何改变文件的权限,布布扣,bubuko.com

在Android java代码中如何改变文件的权限

标签:android   style   c   class   blog   code   

原文地址:http://www.cnblogs.com/nick-zhang/p/3746065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!