Android中数据存储

这里写图片描述

xml存储( 或者叫SharedPreferences存储)

将数据存储到SharedPreferences中

MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView mTextViewRead;
    private EditText mEditText;
    private Button mButtonRead;
    private Button mButtonWrite;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextViewRead= (TextView) findViewById(R.id.textview_read);
        mEditText= (EditText) findViewById(R.id.edittext_write);
        mButtonRead= (Button) findViewById(R.id.button_read);
        mButtonWrite= (Button) findViewById(R.id.button_write);
         mButtonRead.setOnClickListener(this);
        mButtonWrite.setOnClickListener(this);
          @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button_read:
                fromEdit();
//                fromEdit1();
                break;
            case R.id.button_write:
                editToPreferences();
//                editToPreferences1();
                break;
                default:
                break;
        }
    }
    private void fromEdit() {
        SharedPreferences preferences=getSharedPreferences("preferences_test",MODE_PRIVATE);
        String content=preferences.getString("edittext_input","我是默认值");
        mTextViewRead.setText(content);
    }

    private void editToPreferences() {
        SharedPreferences preferences=getSharedPreferences("preferences_test",MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.putString("edittext_input",mEditText.getText().toString());
        editor.commit();
    }
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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/textview_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       />
    <EditText
        android:id="@+id/edittext_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/button_write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="写入数据"/>
    <Button
        android:id="@+id/button_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取数据"/>
        </LinearLayout>
得到SharedPreferences对象的操作

1、Context类中的getSharedPreferences()方法,,此方法接收两个参数,第一个参数用来指定SharedPreferences文件的名称,如果指定的文件不存在则会创建一个,SharedPreferences文件都是存放在/data/data/《package name》/shared_prefs/目录下的。第二个参数用于指定操作模式,主要有两种模式可以选择,MODE_PRIVATE和MODE_MULTI_PROCESS。MODE_PRIVATE仍然是默认的操作模式和直接传入0的效果是一样的,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写。MODE_MULTI_PROCESS则一般是用于会有多个进程对同一个SharedPreferences文件进行读写的情况。

2、得到SharedPreferences对象之后,就可以开始向SharedPreferences文件存储数据了。

1、调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象。
2、向SharedPreferences.Editor对象中添加数据,添加一个布尔型数据就使用putBoolean方法,添加一个字符串则使用putString()方法。
3、调用commit()方法将添加的数据提交,从而完成数据存储操作。

SharedPreferences preferences=getSharedPreferences("preferences_test",MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.putString("edittext_input",mEditText.getText().toString());
        editor.commit();

从SharedPreferences中读取数据

布局文件
 <Button
        android:id="@+id/button_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取数据"/>
主函数
 private void fromEdit() {
        SharedPreferences preferences=getSharedPreferences("preferences_test",MODE_PRIVATE);
        String content=preferences.getString("edittext_input","我是默认值");
        mTextViewRead.setText(content);
    }

文件存储

文件存储是Android中最基本的一种数据存储方式,它不对存储的内容进行任何的格式化处理,所有数据都是原封不动的保存到文件当中的。比较适合用于存储一些简单的文本数据或二进制数据。

将数据存储到文件中

Context类中提供了一个openFileOutput()方法,可以用于将数据存储到指定的文件中,这个方法也接收两个参数,第一个参数是文件名,在文件创建的时候使用的就是这个名称,(这里指定的文件名不可以包含路径,因为所有的文件都是默认存储到/data/data/《package name》/files/目录下的。)。第二个参数是文件的操作模式,主要有两种模式可选,MODE_PRIVATE和MODE_APPEND.其中MODE_PRIVATE是默认的操作模式。表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容,而MODE_APPEND则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件。

private void writeCacheFile() {
        try {
            //hellocache是放在files下面的文件
            FileOutputStream outputStream=openFileOutput("hellocache",MODE_PRIVATE);
            PrintWriter writer=new PrintWriter(new OutputStreamWriter(outputStream));
            writer.write("你好杜永康!");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

总结:通过openFileOutput()方法能够得到一个FileOutputStream对象,,然后在借助它构建出一个OutputStreamWriter对象,接着在使用OutputStreamWriter构建出一个BufferedWriter对象或者是PrintWriter对象。

从文件中读取数据

1、类似于将数据存储到文件中,Context类中还提供了一个openFileInput()方法,用于从文件中读取数据,它只接受一个参数,即只读文件名,然后系统会自动到/data/data/《package name》/files/目录下去加载这个文件,并返回一个FileInputStream对象,得到这个对象之后再通过Java流的方式就可以将数据读取出来。

 private void readCacheFile() {
        try {
            FileInputStream is=openFileInput("hellocache");
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String line=br.readLine();
            while(line!=null){
                Log.d("读取", "" + line);
                line=br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

总结:首先通过openFileInput()方法获取到了一个FileInputStream对象,然后借助它又构建出一个InputStreamReader对象,接着在使用InputStreamReader构建出一个BufferedReader对象,这样我们就可以通过BufferedReader进行一行一行的读取,把文件中所有的文本内容全部读取出来并存放在一个String对象中。最后将读取到的内容返回就可以了。

缓存Cache

创建缓存

   private void CreateCache() {
        //Hi!Tom.txt是放在cache文件下面的
        File file=new File (getCacheDir(),"Hi!Tom.txt");
        if (!file.exists()){
            try {
                file.createNewFile();//如果文件不存在,则创建新文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

SD卡存储

#

 case R.id.button_write_sdcard:
                //Toast.makeText(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT).show();
//Environment.getExternalStorageDirectory()是为了的得到外部存储路径
                File file=new File (Environment.getExternalStorageDirectory(),"helloword.txt");
                if (!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    FileOutputStream outputStream=new FileOutputStream(file);
                    outputStream.write("你好啊,本地存储".getBytes());//将文本写入helloword.txt中
                    outputStream.flush();
                    outputStream.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值