Android:数据持久化

读写普通文本文件:


public class MainActivity extends Activity {
    EditText edit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = (EditText) findViewById(R.id.edit);
        BufferedReader reader = null;
        FileInputStream is;
        StringBuilder content = new StringBuilder();
        try {
            is = openFileInput("TestFileWrite");
            reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        edit.setText(content.toString());
        edit.setSelection(content.toString().length());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String text = edit.getText().toString();
        BufferedWriter writer = null;
        try {
            FileOutputStream os = openFileOutput("TestFileWrite", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write(text);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

使用SharedPreferences对象持久化数据

// SharedPreferences pref = this.getPreferences(Context.MODE_PRIVATE);  //文件名即Activity类名
// SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);  //文件名即主类包名_preferences
        
SharedPreferences pref = this.getSharedPreferences("filename", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("remember_password", true);
editor.putString("username", "admin");
editor.putString("password", "123");
// editor.clear();
editor.commit();

pref.getString("name", "no_name");
pref.getString("password", "no_pass");
pref.getBoolean("remember_password", false);

文件存储位置:/data/data/主类包名/ 目录,主类包名,不一定是当前包名。

posted @ 2019-01-03 13:59  xuejianbest  阅读(185)  评论(0编辑  收藏  举报