Android的各种数据存储方式_part1

Android的各种数据存储方式_part1

内部fils存储、内部cache存储、外部sdcard储存、SharedPreferences储存

内部fils存储、内部cache存储

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="保存到内部存储" />

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="请输入要保存的字符" />

    <Button
        android:id="@+id/btn_save_files"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存到内部存储files目录" />

    <Button
        android:id="@+id/btn_save_cache"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存到内部存储cache目录" />


</LinearLayout>

MainActivity.java

package com.example.innersave;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    EditText etInput;
    Button btnSaveFiles;
    Button btnSaveCache;

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

        etInput = (EditText) findViewById(R.id.et_input);
        btnSaveFiles = (Button) findViewById(R.id.btn_save_files);
        btnSaveCache = (Button) findViewById(R.id.btn_save_cache);

        btnSaveFiles.setOnClickListener(this);
        btnSaveCache.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        String text = etInput.getText().toString().trim();
        // 判断字符不为空
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(getApplicationContext(), "不能为空", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        switch (v.getId()) {
        case R.id.btn_save_files:
            try {
                // 目录在:data/data/包名/files/hello_test.txt
                File innerFilesDir = this.getFilesDir();
                FileOutputStream fos = new FileOutputStream(new File(
                        innerFilesDir, "hello_test.txt"));
                fos.write(text.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case R.id.btn_save_cache:
            try {
                // 目录在:data/data/包名/cache/hello_test.txt
                File innerCacheDir = this.getCacheDir();
                FileOutputStream fos = new FileOutputStream(new File(
                        innerCacheDir, "hello_test.txt"));
                fos.write(text.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            break;
        default:
            break;
        }
    }

}

注意

  1. 存储在手机内部不需要配置权限
  2. “data/data/包名/cache/” 和 “data/data/包名/files/” 目录在app覆盖安装的时候不会被删除,但是在app被卸载的时候会被删除。
  3. 如下的文件的创建方式,遇到重名文件会直接覆盖。

    FileOutputStream fos = new FileOutputStream(new File(
                    innerFilesDir, "hello_test.txt"));
    fos.write(text.getBytes());
    fos.close();
    

外部sdcard储存

示例

public void writeSdcard() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // 获取sd卡的剩余空间
        long usableSpace = Environment.getExternalStorageDirectory()
                .getUsableSpace();
        Log.d("ziru", "usableSpace: " + usableSpace);
        // 获取sd卡的目录
        File path = Environment.getExternalStorageDirectory();

        // 保存存到sd卡
        try {
            FileOutputStream fos = new FileOutputStream(new File(path,
                    "info.txt"));
            String str = "hello sdcard";
            fos.write(str.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        Log.d("ziru", "保存失败, 请检查sd卡");
    }
}

public void readSdcard() {
    File path = Environment.getExternalStorageDirectory();
    BufferedReader br;
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(
                new File(path, "info.txt"))));
        String line = br.readLine();

        Log.d("ziru", "info.txt的第一行数据 = " + line);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

权限

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

SharedPreferences储存

  1. SharedPreferences是Android提供的生成和解析xml文件的包装类。
  2. xml文件在:data/data/包名/shared_prefs/目录下。

示例

public void writeSharedPreferences() {
    // 初始化SharedPreferences
    SharedPreferences sp = this.getSharedPreferences("config",
            Context.MODE_PRIVATE);
    // 通过SharedPreferences获取编辑器
    Editor editor = sp.edit();
    // 写入数据
    editor.putString("qq", "1111");
    editor.putString("pwd", "123456");
    editor.putBoolean("isChecked", true);
    // 提交数据
    editor.commit();
}

public void readSharedPreferences() {
    // 初始化SharedPreferences
    SharedPreferences sp = this
            .getSharedPreferences("config", MODE_PRIVATE);
    // 读取数据
    String qq = sp.getString("qq", "");// 如果不存在返回""
    String pwd = sp.getString("pwd", "");// 如果不存在返回""
    boolean isChecked = sp.getBoolean("isChecked", false);// 如果不存在返回false

    Log.d("ziru", "qq = " + qq + ", pwd = " + pwd + ", isCheck = "
            + isChecked);
}

封装好的工具类

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharePrefrence的封装
 */
public class PrefUtils {

    private static SharedPreferences mPrefs;

    public static void putBoolean(Context ctx, String key, boolean value) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        mPrefs.edit().putBoolean(key, value).commit();
    }

    public static boolean getBoolean(Context ctx, String key, boolean defValue) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        return mPrefs.getBoolean(key, defValue);
    }

    public static void putString(Context ctx, String key, String value) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        mPrefs.edit().putString(key, value).commit();
    }

    public static String getString(Context ctx, String key, String defValue) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        return mPrefs.getString(key, defValue);
    }

    public static void putInt(Context ctx, String key, int value) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        mPrefs.edit().putInt(key, value).commit();
    }

    public static int getInt(Context ctx, String key, int defValue) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        return mPrefs.getInt(key, defValue);
    }

    public static void remove(Context ctx, String key) {
        if (mPrefs == null) {
            mPrefs = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
        }

        mPrefs.edit().remove(key).commit();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值