Android下的文件访问权限
16lz
2021-01-23
在上一篇文章《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中找到这些文件,然后查看他们的权限
更多相关文章
- Android 读取raw下的txt文件
- Android studio cmd命令行操作数据库文件导出,导入
- Android中的文件的读取方法
- android的文件存储
- 修改Android签名文件keystore作为eclipse默认debug签名文件
- Android更改桌面应用程序launcher的两种方式
- Android本地应用程序应用方式介绍
- android sdk 版本问题 R文件问题