其他分享
首页 > 其他分享> > 本地文件存储

本地文件存储

作者:互联网

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void operate(View v){
        Intent it=null;
        switch (v.getId()){
            case R.id.share_btn:
                it = new Intent(this,ShareActivity.class);
                break;
            case R.id.external_btn:
                it = new Intent(this,ExternalActivity.class);
                break;
            default:
                it = new Intent(this,InternalActivity.class);
                break;
        }//开启其他活动
        startActivity(it);
    }
}
/*SharePreference  持久化数据的更新   不能用在多进程,Google为多进程提供了一个数据同步互斥方案
                                                 ,那就是基于Binder实现的ContentProvider
对应的xml文件位置一般都在程序私有目录/data/data/包名/shared_prefs目录下,后缀一定是.xml
    、用于存放一些类似登录的配置信息、通过类似键值对的方式存储数据、MODE_PRIVATE常用
    该文件也可以被其他activity调用,只要找到对应的文件。
SharedPreferences接口、SharedPreferences.Editor存储信息并提交。
 */
public class ShareActivity extends AppCompatActivity {

    private EditText accEdt, pwdEdt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);

        accEdt = findViewById(R.id.acc_edt);
        pwdEdt = findViewById(R.id.pwd_edt);

        //SharePreference的读取,每次运行先自动读取
        //①获取SharePreference对象(参数1:文件名  参数2:模式)
        SharedPreferences share = getSharedPreferences("myshare", MODE_PRIVATE);
        //②根据key获取内容(参数1:key   参数2:当对应key不存在时,返回参数2的内容作为默认值)
        String accStr = share.getString("account", "");//账户
        String pwdStr = share.getString("pwd", "");

        //set到控件
        accEdt.setText(accStr);
        pwdEdt.setText(pwdStr);

        findViewById(R.id.login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1.获取两个输入框的内容
                String account = accEdt.getText().toString();
                String pwd = pwdEdt.getText().toString();
                //2.验证(admin  123)    对比账户名字和密码
                if (account.equals("admin") && pwd.equals("123")) {

                    //2.1存储信息到SharePreference
                    //①获取SharePreference对象(参数1:文件名,本身就是xml文件   参数2:模式)
                    SharedPreferences share = getSharedPreferences("myshare", MODE_PRIVATE);
                    //②获取Editor对象
                    SharedPreferences.Editor edt = share.edit();
                    //③存储信息
                    edt.putString("account", account);
                    edt.putString("pwd", pwd);
                    //④指定提交操作
                    edt.commit();

                    Toast.makeText(ShareActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                } else {
                    //2.2验证失败,提示用户
                    Toast.makeText(ShareActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ShareActivity">

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="账号:"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toStartOf="@+id/guideline5" />

    <EditText
        android:id="@+id/acc_edt"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintStart_toStartOf="@+id/guideline5" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="密码:"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/guideline4"
        app:layout_constraintEnd_toStartOf="@+id/guideline5" />

    <EditText
        android:id="@+id/pwd_edt"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:inputType="textPassword"
        app:layout_constraintBottom_toTopOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="@+id/guideline5" />

    <Button
        android:id="@+id/login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="登录"
        app:layout_constraintTop_toTopOf="@+id/guideline4" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="93dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="179dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="88dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
/*
外部存储,实现写入和读出,动态权限申请  在Manifest加权限<uses-permission
对于外部存储私有目录的读写,不用获取权限就可以用,file和cache,应用数据和应用缓存所在目录
 */
public class ExternalActivity extends AppCompatActivity {

    EditText infoEdt;
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_external);

        infoEdt = findViewById(R.id.info_edt);
        txt = findViewById(R.id.textView);

        //动态权限
        //检查自己是否有写入外部存储权限
        int permisson = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permisson != PackageManager.PERMISSION_GRANTED) {//没有权限
            //动态去申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

    }

    //申请权限的时候会触发该方法,通过对比请求码来完成一些事情
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            //做事情
        }
    }

    public void operate(View v) {
        //获取路径
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/imooc.txt";
        Log.e("TAG", path);
        //用来判断内存卡存在
        //if(Environment.getExternalStorageState().equals("mounted"))
        switch (v.getId()) {
            case R.id.save_btn:
                //新建文件
                File f = new File(path);
                try {
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    //文件输出流(路径,是否追加)
                    FileOutputStream fos = new FileOutputStream(path, true);
                    //获取输入框的内容并以字符串类型
                    String str = infoEdt.getText().toString();
                    //以字节流方式写入输出流
                    fos.write(str.getBytes());
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
                break;
            //读取并显示
            case R.id.read_btn:
                try {
                    FileInputStream fis = new FileInputStream(path);
                    byte[] b = new byte[1024];
                    int len = fis.read(b);
                    String str2 = new String(b, 0, len);
                    txt.setText(str2);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ExternalActivity">


    <EditText
        android:id="@+id/info_edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="22dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:gravity="left|top"
        android:hint="请输入待存储的内容..."
        android:maxLines="12"
        android:minLines="12"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/read_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:onClick="operate"
        android:text="读取"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/save_btn"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/save_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:onClick="operate"
        android:text="保存"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="176dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
内部存储  两个文件夹:app和data    file和cache
public class InternalActivity extends AppCompatActivity {
    EditText edt;
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_internal);
        
        edt = findViewById(R.id.editText);
        txt = findViewById(R.id.textView);
    }

    public void operate(View v){

        //  data/data/包名/files
        //   getCacheDir()    data/data/包名/cache
        File f = new File(getFilesDir(),"getFilesDirs.txt");
        switch (v.getId()){
            case R.id.save_btn:
                try {
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write(edt.getText().toString().getBytes());
                    fos.close();//多了个close
                }catch (IOException e){
                    e.printStackTrace();
                }
                break;
            case R.id.read_btn:
                try {
                    FileInputStream fis = new FileInputStream(f);
                    byte[] b = new byte[1024];
                    int len = fis.read(b);
                    String str2 = new String(b,0,len);
                    txt.setText(str2);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}

布局文件一样。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
    tools:ignore="ProtectedPermissions" />

标签:文件,存储,String,void,public,本地,new,edt,id
来源: https://blog.csdn.net/qq_41596457/article/details/118652811