天天看点

[android] android下文件访问的权限

/**************2016年5月4日 更新**************************/

知乎:android编程中写文件(例如a.txt)后存在手机哪个位置啊?

用FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(content.getBytes()); fos.close(); 建立新文件并写入后,在手机中找不到这个文件,用了搜索也没有这个文件。请问有大神知道文件会自动存在哪?或者应该用什么方法来创建一个根目录下的文件?

酱油瓶:

不指定的话,在/data/ data/ 应用包名 文件夹里

手机没有root权限的话,data下的数据是看不到的

/****************************************************/

1. 使用Context上下文对象调用openFileOutput(文件名,mode)可以在/data/data/包名/ 下创建一个文件输出对象,其中mode有

Context.MODE_PRIVATE(私有方式),

Context.MODE_WORLD_READABLE(可读)

Context.MODE_WORLD_WRITEABLE(可写)

当别的应用读取私有文件时会报fileNotFound premission den,

别的应用可以读取可读文件和公开文件

2. 单选框组<RadioGroup><RadioButton>,默认竖直方向android:orientation=”horizontal”水平,获取选中的值,RadioGroup对象的getCheckedRadioButtonId(),可以得到被选中的RadioButton

@suppressLint 是压制警告的作用

3. Linux系统下的文件权限,10个字符,----------

一般情况下android下每一个应用都是一个独立的用户对应一个独立的组

0位置 - 代表文件,d代表目录

1-3位置 当前用户 r 可读,w可写,x可执行

查看当前用户和组,cmd进入adb shell,cd到/data/data 执行ls -l就能看到

4-6位置 当前用户所在的组 r 可读,w可写,x可执行

7-9位置 其他用户的权限,别的应用访问这个文件相当于这个角色,

- - - - - - - - - - 对应0 000

- rw- - - - - - - 对应0 600

- rw- rw- rw- 对应0 666 在shell下可以使用chmod 666 private.txt 来更改权限

业务代码修改:

/**
     * 保存用户名和方法的业务方法
     * @param context 上下文
     * @param username 用户名
     * @param password 方法
     * @param mode 1私有 2可读 3可写 4公开
     * @return
     */
    @SuppressWarnings("deprecation")
    public static boolean saveUserInfo(Context context,String username,String password,int mode){
        File file=new File(context.getFilesDir(),"info1.txt");
        try {
            FileOutputStream fos = null;
            switch (mode) {
            case 1:
                fos=context.openFileOutput("private.txt", Context.MODE_PRIVATE);
                break;
            case 2:
                fos=context.openFileOutput("readable.txt", Context.MODE_WORLD_READABLE);
                break;
            case 3:
                fos=context.openFileOutput("writeable.txt", Context.MODE_WORLD_WRITEABLE);
                break;
            case 4:
                fos=context.openFileOutput("private.txt", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
                break;
            default:
                break;
            }
            String info=username+"##"+password;
            fos.write(info.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        
    }           

复制

继续阅读