读取外部存储和直接IO写入文档

进行对SD卡的资料获取和写入操作

1.检测外置SD卡的状态

        String state=
        Environment.getExternalStorageState();
        Log.i("TAG", "state="+state);

        if(!state.equals(Environment.MEDIA_MOUNTED)||
        Environment.isExternalStorageRemovable()){
        Toast.makeText(this, "请确保SDCARD可用", 0).show();
        return;
        }

2.获得外置sdcard的公有存储目录

        //2.1获得外部存储的根目录
        File sdcard=//mnt/sdcard
        Environment.getExternalStorageDirectory();
        Log.i("TAG", "sdcard="+sdcard.getPath());
        //2.2获得外部存储的子目录
        File picDir=//mnt/sdcard/Pictures
        Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);
        Log.i("TAG", "picDir="+picDir.getPath());

2.获得外置sdcard的私有存储目录(此目录的获得需要添加写权限)

//获得缓存目录
        //getExternalCacheDir();//mnt/sdcard/android/data/项目包/cache
        File sdcardText=getExternalFilesDir("mydir");//目录不存在底层会创建
        //3.获得外置sdcard的可用空间大小
        StatFs sf=new StatFs(sdcardText.getPath());

        String text="helloworld";
        if(text.getBytes().length>
        sf.getAvailableBlocks()*sf.getBlockSize()){
            Toast.makeText(this, "磁盘空间不足", 0).show();
            return;
        }

3.获得外置sdcard的可用空间大小

 StatFs sf=new StatFs(sdcard.getPath());
        //sf.getBlockCount() 块的总数量
        //sf.getFreeBlocks() 空闲块数>=可用块
        //sf.getAvailableBlocks() 可用块数
        //sf.getBlockSize(); 块大小

        double totalSize=//M
        sf.getBlockCount()*sf.getBlockSize()*1.0/1024/1024;

        Log.i("TAG", "totalSize="+totalSize);

        String text="helloworld";
        if(text.getBytes().length>
        sf.getAvailableBlocks()*sf.getBlockSize()){
        Toast.makeText(this, "磁盘空间不足", 0).show();
        return;
        }

直接IO写入数据

OutputStream out=null;
        try{
            out=new FileOutputStream(new File(sdcardText,"d1.txt"));
            out.write(text.getBytes());
            Log.i("TAG", "write ok!");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(out!=null)try{out.close();}catch(Exception e){}
        }

获取私有数据目录需要添加如下权限到清单配置文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值