• 14_把文件存放在SDCard


    权限添加

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

        /**
         * 保存到SD卡
         * @param filename
         * @param content
         * @throws Exception
         */
        public void saveToSDCard(String filename, String content) throws Exception{
            // TODO Auto-generated method stub
            //    MODE_PRIVATE:创建出来的文件仅能被本应用访问,另外采用私有模式创建的文件写入文件中的内容会覆盖原文件的内容
            File file = new File(Environment.getExternalStorageDirectory(), content);
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.close();
        }    
        
        private final class ButtonClickListener implements View.OnClickListener{
            
            public void onClick(View v){
                String filename = filenameText.getText().toString();
                String content = contentText.getText().toString();
                FileService service = new FileService(getApplicationContext());
                try {
                    //    方法1:写入手机内存
                    //service.save(filename, content);
                    //Toast.makeText(getApplicationContext(),"R.string.success"/*R.string.success*/, Toast.LENGTH_SHORT);
                    //    方法2:写入SD卡
                    if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
                        service.saveToSDCard(filename, content);
                        Toast.makeText(getApplicationContext(),"R.string.success"/*R.string.success*/, Toast.LENGTH_SHORT);
                    }
                    else{
                        Toast.makeText(getApplicationContext(),"sd failed"/*R.string.success*/, Toast.LENGTH_SHORT);
                    }
                        
                    
                } catch (Exception e) { 
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "failed"/*R.string.fail*/, Toast.LENGTH_SHORT);
                    e.printStackTrace();
                }
                
                
            }
        }
  • 相关阅读:
    day 6 敌机
    day 11 绘制轮廓
    day 10 形态学处理 膨胀
    day 5 飞机发射子弹 难点??
    激活Navicat?如何注册Navicat?
    Gradle DSL method found: ‘android()’错误
    腾讯sdk配置
    Android模拟器报"Failed To Allocate memory 8"错误的解决办法
    文件上传工具swfupload[转]
    35个jquery技巧[转]
  • 原文地址:https://www.cnblogs.com/carl2380/p/4159604.html
Copyright © 2020-2023  润新知