android常见数据存储方式一

android数据的存储大致可以分为文件存储方式和数据库存储方式。

今天先简单讲述在android系统中文件数据存储方式,后面再讲解数据库的存储方式。文件存储无非就是牵涉到文件流,文件流直接导向就是文件的目录,android系统中针对应用程序常见以下几个目录:

1.data/data/{packageName}/files/{fileName}                  

2.data/data/{packageName}/cache/{fileName}               

3.data/data/{packageName}/shared_prefs/{fileName}

4.storage/emulated/0/{fileName}

由于这关系到文件读写权限的问题,所以一定要记得动态申请权限。



public class MainActivity extends AppCompatActivity {
    private EditText et_userName;
    private EditText et_password;
    public static final String PREFS_NAME = "MyPrefsFile";
    private static String USER_NAME = "prefs_username";
    private static String USER_PASSWORD = "prefs_password";

    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private List<String> mPermissionsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_userName = (EditText) findViewById(R.id.et_userName);
        et_password = (EditText) findViewById(R.id.et_password);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mPermissionsList.clear();
            for (int i = 0; i < permissions.length; i++) {
                if (ActivityCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionsList.add(permissions[i]);
                }
            }

            if (!mPermissionsList.isEmpty()) {
                String[] permissions = mPermissionsList.toArray(new String[mPermissionsList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                        Log.e("antier", showRequestPermission + "");
                        if (!showRequestPermission) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", this.getPackageName(), null);
                            intent.setData(uri);
                            this.startActivity(intent);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    public void onClickSaveFileDir(View view) {
        String userName = et_userName.getEditableText().toString();
        String password = et_password.getEditableText().toString();

        File file = new File(getFilesDir(), "file.txt");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write((userName + "&" + password).getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onClickSaveCacheDir(View view) {
        String userName = et_userName.getEditableText().toString();
        String password = et_password.getEditableText().toString();
        File file = new File(getCacheDir(), "file.txt");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write((userName + "&" + password).getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onClickSaveExternalDir(View view) {
        String userName = et_userName.getEditableText().toString();
        String password = et_password.getEditableText().toString();

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getExternalStorageDirectory(), "file.txt");
            Log.e("antier", file.getPath());
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write((userName + "&" + password).getBytes());
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "写入失败!", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "请检查外部存储设备!", Toast.LENGTH_LONG).show();
        }
    }

    public void onClickSaveSharedPreferences(View view) {
        String userName = et_userName.getEditableText().toString();
        String password = et_password.getEditableText().toString();

        SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(USER_NAME, userName);
        editor.putString(USER_PASSWORD, password);
        editor.commit();

    }

    public void onClickReadFileDir(View view) {

        try {
            FileInputStream fileInputStream = new FileInputStream(getFilesDir().getPath() + File.separator + "file.txt");
            Log.e("antier", getFilesDir().getPath() + File.separator + "file.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String content = bufferedReader.readLine();
            String[] info = content.split("&");
            et_userName.setText(info[0]);
            et_password.setText(info[1]);

        } catch (IOException e) {
            Toast.makeText(this, "文件读取失败!", Toast.LENGTH_LONG).show();
        }
    }

    public void onClickReadCacheDir(View view) {
        try {
            FileInputStream fileInputStream = new FileInputStream(getCacheDir().getPath() + File.separator + "file.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String content = bufferedReader.readLine();
            String[] info = content.split("&");
            et_userName.setText(info[0]);
            et_password.setText(info[1]);
        } catch (IOException e) {
            Toast.makeText(this, "文件读取失败!", Toast.LENGTH_LONG).show();
        }
    }

    public void onClickReadExternalDir(View view) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                FileInputStream fileInputStream = new FileInputStream(Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "file.txt");
                Log.e("antier", Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "file.txt");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                String content = bufferedReader.readLine();
                String[] info = content.split("&");
                et_userName.setText(info[0]);
                et_password.setText(info[1]);

            } catch (IOException e) {
                Toast.makeText(this, "文件读取失败!", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "未发现SD卡", Toast.LENGTH_LONG).show();
        }
    }

    public void onClickReadSharedPreferences(View view) {
        SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        et_userName.setText(settings.getString(USER_NAME, ""));
        et_password.setText(settings.getString(USER_PASSWORD, ""));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值