android保存文件到SD卡中

想把文件保存到SD卡中,一定要知道SD卡的路径,有人说可以用File explore来查看,这种方法不太好,因为随着android版本的升级,SD卡的路径可能会发生改变。在1.6的时候SD的路径是/sdCard。后续版本都改成了mnt/sdCard。所有还是使用API来获取:

Environment.getExternalStorageDirectory()


另外,在保存之前要判断SD卡是否已经安装好,并且可读写:

//判断SDcard是否存在并且可读写
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    service.saveToSDCard(filename,filecontent);
                    Toast.makeText(getApplicationContext(), R.string.success, 1).show();
                }else{
                    Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
                }


查看完整代码:

    /**
     * 保存到SD卡
     * @param filename
     * @param filecontent
     * @throws Exception
     */
    public void saveToSDCard(String filename, String filecontent)throws Exception{
        File file = new File(Environment.getExternalStorageDirectory(),filename);
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(filecontent.getBytes());
        outStream.close();
    }    


    @Override
        public void onClick(View v) {
            EditText filenameText = (EditText)findViewById(R.id.filename);
            EditText filecontentText = (EditText)findViewById(R.id.filecontent);
            String filename = filenameText.getText().toString();
            String filecontent = filecontentText.getText().toString();
            FileService service = new FileService(getApplicationContext());
            try {
                //判断SDcard是否存在并且可读写
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    service.saveToSDCard(filename,filecontent);
                    Toast.makeText(getApplicationContext(), R.string.success, 1).show();
                }else{
                    Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
                }
                
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
                e.printStackTrace();
            }
            Toast.makeText(getApplicationContext(), R.string.success, 1).show();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值