Android下的文件访问权限

在上一篇文章《Android——用户登陆及用户名和密码的保存》中讲到了将用户登陆的数据保存到对应的文件中,在保存文件时我们编写了以下的一段代码:

public boolean saveToRom(String password,String username,String filename) throws Exception{
        //以私有的方式打开一个文件
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
        String result = username+":"+password;
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
        return true;
    }

在此代码中,我们使用Context.MODE_PRIVATE来进行文件的保存,使用此模式保存的文件不能被其他的应用程序所访问,在其中还有其他的保存模式:

    public boolean saveToRom(String password,String username,String filename) throws Exception{
        //以私有的方式打开一个文件
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_APPEND);
        String result = username+":"+password;
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
        return true;
    }

此时的模式被改为了Context.MODE_APPEND模式,表示在文件的后面追加内容,不会将文件的内容给覆盖掉,同时,声明为此模式的文件不能被其他程序进行读写。
对于文件的模式我们也可以声明为对外部程序可读和可写:

对外部程序可读:

public boolean saveToRom(String password,String username,String filename) throws Exception{
        //以私有的方式打开一个文件
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
        String result = username+":"+password;
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
        return true;
    }

此时创建的文件在外部只能对其进行读,而不能进行写。

对外部程序可写:

public boolean saveToRom(String password,String username,String filename) throws Exception{
        //以私有的方式打开一个文件
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
        String result = username+":"+password;
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
        return true;
    }

此时创建的文件在外部只能对其写,而不能对其他读取。
实际上对于以上的几种模式,在Android底层实现是在创建文件的时候就会声明文件的操作权限,下面是具体的一张截图:

在上图中我们可以清楚的看到在文件保存时会对文件的权限进行一定的限制的。

我们也可以在adb shell中找到这些文件,然后查看他们的权限

原文地址:https://www.cnblogs.com/wukong65/p/3060524.html