IT源码网

安卓数据持久化讲解

flyfish 2021年02月16日 手机开发 198 0
//文件类型

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); 

  

发布评论
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

安卓倒计时讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。