• android如何操作sd卡


    //申明SharedPreferences对象

    SharedPreferences mSharedPreferences;
    SharedPreferences.Editor mEditor;
    mSharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
    mEditor = mSharedPreferences.edit();

    //在主方法里写一个点击事件保存数据
    Button left = (Button) findViewById(R.id.left);
    left.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    WriteToSd();
    mEditor.putString("user",editText1.getText().toString());
    mEditor.putString("passWorld",editText2.getText().toString());
    mEditor.commit();
    }
    });

    user = mSharedPreferences.getString("user",null);
    passWorld = mSharedPreferences.getString("passWorld",null);
    editText1.setText(user);
    editText2.setText(passWorld);



    //读取文件
    private void ReadFromSd(){
    String s = Environment.getExternalStorageState();
    File root = Environment.getExternalStorageDirectory();
    File TargetDir = new File(root,super.getPackageName());
    ObjectInputStream ois = null;
    if (TargetDir.exists()){
    try {
    ois = new ObjectInputStream(new FileInputStream(new File(TargetDir+"/liu.txt")));
    People people = (People) ois.readObject();
    Toast.makeText(getApplication(),people.getUser().toString()+people.getPwd().toString(),Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }finally {
    try {
    ois.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }else {
    Toast.makeText(getApplication(),"false",Toast.LENGTH_SHORT).show();
    }
    }
    写入文件
    private void WriteToSd(){
    String s = Environment.getExternalStorageState();
    ObjectOutputStream oos = null;
    if (s.equals(Environment.MEDIA_MOUNTED)){//判断是否有权限,记得在清单文件里声明权限,6.1版本之后的手机可能还是不行
    File root = Environment.getExternalStorageDirectory();
    File tag = new File(root ,super.getPackageName());
    if (!tag.exists()){ //判断文件是否存在
                tag.mkdir();
    }
    try {
    oos = new ObjectOutputStream(new FileOutputStream(new File(tag,"liu,txt")));
    People people = new People("liu","yifan");
    oos.writeObject(people);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }



    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jredu.liuyifan.fragmentapplication">//写在这里面
    //两个权限
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  • 相关阅读:
    【Flutter 实战】1.20版本更新及新增组件
    【Flutter 实战】各种各样形状的组件
    【Flutter 实战】全局点击空白处隐藏键盘
    Flutter —布局系统概述
    【Flutter 实战】17篇动画系列文章带你走进自定义动画
    lvs负载简介,原理,常见使用案例及Keepalived高可用
    02 . MongoDB复制集,分片集,备份与恢复
    Go之Casbin简介,安装,模型,存储,函数
    govendor包管理及Go项目热加载
    教你三招快速文件批量重命名方法
  • 原文地址:https://www.cnblogs.com/lyf2458857555/p/5883928.html
Copyright © 2020-2023  润新知