安卓数据持久化
//文件类型
void save(String string){ FileOutputStream out=null; BufferedWriter writer = null; try{ out = openFileOutput("data", Context.MODE_APPEND); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(string); }catch (IOException e) { e.printStackTrace(); }finally { try { if(writer!=null){ writer.close(); } }catch (IOException e){ e.printStackTrace(); } } } public String load(){ FileInputStream in =null; BufferedReader reader = null; StringBuilder content= new StringBuilder(); try{ in =openFileInput("data"); reader =new BufferedReader(new InputStreamReader(in)); String line=""; while ((line=reader.readLine())!=null){ content.append(line); } }catch (IOException e){ e.printStackTrace(); }finally { if(reader!=null){ try{ reader.close(); }catch (IOException e){ e.printStackTrace(); } } } return content.toString(); }
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit(); editor.putString("name","tom"); editor.putInt("age",28); editor.putBoolean("married",false); editor.apply(); SharedPreferences pref= getSharedPreferences("data",MODE_PRIVATE); String name = pref.getString("name",""); int age = pref.getInt("age",0); Boolean married = pref.getBoolean("married",false); Log.d(TAG, "onCreate: "+name); Log.d(TAG, "onCreate: "+age); Log.d(TAG, "onCreate: "+married);