Android文件路径小结

来源:互联网 发布:网络课程交易 编辑:程序博客网 时间:2024/05/19 04:07

Android文件存储可分为内部存储和外部存储。内部存储(InnerStorage)应用私有,应用被卸载,文件删除。外部储存(ExternalStorage)可分为外部公用区域(App卸载文件保留)和应用私有区域(App卸载文件删除)。

内部存储:

    //内部缓存文件 app卸载或空间不足,数据删除        File file6 = this.getCacheDir();        Log.e("file6", file6.toString());        //获取在其中存储内部文件的文件系统目录的绝对路径,文件私有,app卸载文件会被删除        File file7 = this.getFilesDir();        Log.e("file7", file7.toString());        //创建文件        File file9 = new File(this.getFilesDir(), "file9");        if (!file9.exists()) {            try {                file9.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        OutputStream out = null;        try {            out = openFileOutput("file8", Context.MODE_PRIVATE);            out.write(new String("test").getBytes());        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (out != null) {                try {                    out.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        String[] files = this.fileList();        for (String file : files) {            Log.e("innerstorage", "file is" + file);        }    }
打印log如下:

总结:

1文件操作只需要向函数提供文件名

2不用自己创建文件对象和输入输出流,根据文件名可获取文件对象、输入输出流

3对于路径操作返回文件对象

4文件私有

外部存储:

  //外部储存私有,app卸载,文件被删除,参数识别保存数据类型,不会被媒体扫描器扫        File filea = this.getExternalFilesDir(Environment.DIRECTORY_MUSIC);        Log.e("filea", filea.toString());        //外部储存缓存目录,app卸载,会被干掉        File filec = this.getExternalCacheDir();        Log.e("filec", filec.toString());        //外部存储器中公用目录,参数可以正确配置文件类型,系统媒体扫描类型可以准确地归类文件        File file1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);        Log.e("file1", file1.toString());        //用户数据目录        File file2 = Environment.getDataDirectory();        Log.e("file2", file2.toString());        //下载缓存目录        File file3 = Environment.getDownloadCacheDirectory();        Log.e("file3", file3.toString());        //外部存储根目录        File file4 = Environment.getExternalStorageDirectory();        Log.e("file4", file4.toString());
log如下:

总结:

1Android4.4版本以前需要声明权限

2使用前需要判断外部储存器是否可用

3公共文件Public files:文件是可以被自由访问,且文件的数据对其他应用或者用户来说都是由意义的,当应用被卸载之后,其卸载前创建的文件仍然保留,并可以被媒体扫描分类

4私有区域文件类似于文件内部存储,应用卸载文件会被删除。


0 0
原创粉丝点击