Android数据存储2 文件存储

本文聚焦移动开发,介绍应用的存储方式。包括内部存储,如私有文件存储、自定义路径存储和缓存文件存储及对应文件路径;还阐述扩展存储(sd卡),涉及权限、获取sd卡状态、根路径,以及提供sd卡工具类用于读写操作。

1.内部存储(私有的,其他程序不能获取)

a.

存:FileOutputStream fos = openFileOutput("file", MODE_PRIVATE);

读:  FileInputStream fis = openFileInput("file");

文件路径:data/data/当前应用程序包名/files/文件

b.自定义路径

Sting filePath = "data/data/当前应用程序包名/文件" 

FileOutputStream fos = new FileOutputStream(filePath);

File file = new File(getFileDir(), "文件");    //    getFileDir() = 文件路径:data/data/当前应用程序包名/files

c.缓存文件

getCacheDir() = 文件路径:data/data/当前应用程序包名/cache

2.扩展存储(sd卡) 公有的

a.权限:

    READ_EXTERNAL_STORAGE、WRITE_...、MOUNT_UNMOUNT_FILESYSTEMS(对sd卡读写和对sd卡文件夹创建删除)

b.获取当前sd卡状态

    return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());

c.sd卡根路径

    String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();

    File.separator =    /

d.sd卡工具类

    public class SDUtils{

        public static void writeToSD(String dirPath, String fileName, byte[] bytes) {

            if(isSdOK()) {

                File dir = new File(Environment.getExternalStorageDirectory(), dirPath);

                if(!dir.exists()) {

                    dir.mkdirs();

                }

                File destFile = new File(dir, fileName);

                FileOutputStream fos = new FileOutputStream(destFile);

                fos.write(bytes);

                finally { fos.close(); }

            } else {

                Log.i("sd卡","sd卡异常")

            }

        }

        private static boolean isSdOK() { ... }

        public static byte[] readFromSd(String path) {

            if(isSdOK()) {

                FileInputStream fis = null;

                ByteArrayOutputStream baos = null;

                ...

                return baos.toByteArray();

            }

        }

    }

转载于:https://my.oschina.net/glfei/blog/3025569

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值