《Android 学习笔记 之 数据存储》

Android 学习笔记 之 数据存储

任务需求:

  • 使用代码动态生成六个按钮,点击按钮完成相应的数据读写,并观察生成的文件位置。
  • 效果图如下:
  • 在这里插入图片描述

核心代码

package com.example.sy4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

    Button[] buttons = new Button[6];
    String[] texts = { "内部写", "内部读", "写SD卡", "读SD卡", "写偏好", "读偏好" };
    String filename = "data.txt";
    String content = "杨侃";

    FileOutputStream fos;
    DataOutputStream dos;
    FileInputStream fis;
    DataInputStream dis;
    String state;
    File SDPath;
    File file;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        LinearLayout linearLayout = findViewById(R.id.linear);

        state = Environment.getExternalStorageState();
        sp = getSharedPreferences("data", MODE_PRIVATE);

        for (int i = 0; i < 6; i++) {
            buttons[i] = new Button(this);
            buttons[i].setText(texts[i]);
            buttons[i].setTag(i + 1);
            buttons[i].setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
            linearLayout.addView(buttons[i]);
            buttons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int tag = (Integer) v.getTag();
                    switch (tag) {
                        case 1:
                            try {
                                fos = openFileOutput(filename, MODE_PRIVATE);
                                dos = new DataOutputStream(fos);
                                dos.writeUTF(content);
                                dos.close();
                                fos.close();
                                Log.i("log", "执行了内部写!");
                                Toast.makeText(MainActivity.this, "执行了内部写!", Toast.LENGTH_SHORT).show();
                            }catch (Exception e) {
                                System.out.printf("程序出错了!");
                                e.printStackTrace();
                            }
                            break;
                        case 2:
                            try {
                                fis = openFileInput(filename);
                                dis = new DataInputStream(fis);
                                String result = dis.readUTF();
                                Log.i("log", "执行了内部读,内容为:" + result);
                                Toast.makeText(MainActivity.this, "执行了内部读,内容为:" + result, Toast.LENGTH_SHORT).show();
                                dis.close();
                                fis.close();
                            }catch (Exception e) {
                                System.out.printf("程序出错了!");
                                e.printStackTrace();
                            }
                            break;
                        case 3:
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                SDPath = Environment.getExternalStorageDirectory();
                                file = new File(SDPath, filename);
                                try {
                                    fos = new FileOutputStream(file);
                                    dos = new DataOutputStream(fos);
                                    dos.writeUTF(content);
                                    dos.close();
                                    fos.close();
                                    Log.i("log", "执行了写SD卡");
                                    Toast.makeText(MainActivity.this, "执行了写SD卡", Toast.LENGTH_SHORT).show();
                                }catch (Exception e) {
                                    System.out.printf("程序出错了!");
                                    e.printStackTrace();
                                }
                            }
                            break;
                        case 4:
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                SDPath = Environment.getExternalStorageDirectory();
                                file = new File(SDPath, filename);
                                try {
                                    fis = new FileInputStream(file);
                                    dis = new DataInputStream(fis);
                                    String result = dis.readUTF();
                                    dis.close();
                                    fis.close();
                                    Log.i("log", "执行了读SD卡,内容为:" + result);
                                    Toast.makeText(MainActivity.this, "执行了读SD卡,内容为:" + result, Toast.LENGTH_SHORT).show();
                                }catch (Exception e) {
                                    System.out.printf("程序出错了!");
                                    e.printStackTrace();
                                }
                            }
                            break;
                        case 5:
                            editor = sp.edit();
                            editor.putString(filename, content);
                            editor.commit();
                            try {
                                fos = openFileOutput(filename, MODE_PRIVATE);
                                dos = new DataOutputStream(fos);
                                dos.writeUTF(content);
                                dos.close();
                                fos.close();
                                Log.i("log", "执行了写偏好");
                                Toast.makeText(MainActivity.this, "执行了写偏好", Toast.LENGTH_SHORT).show();
                            }catch (Exception e) {
                                System.out.printf("程序出错了!");
                                e.printStackTrace();
                            }
                            break;
                        case 6:
                            String data = sp.getString(filename, "");
                            Log.i("log", "执行了读偏好,内容为:" + data);
                            Toast.makeText(MainActivity.this, "执行了读偏好,内容为:" + data, Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            });
        }
    }
}

清单文件中权限的配置

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

在这里插入图片描述

布局文件

在这里插入图片描述

在这里插入图片描述

日志查看

在这里插入图片描述

观察生成的文件位置

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yk_ddm/article/details/115359505