标签:
1 public class MainActivity extends Activity 2 { 3 private EditText et; 4 5 // 6 //创建活动时读取是否有上次保存的内容 7 // 8 @Override 9 protected void onCreate(Bundle savedInstanceState) 10 { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main); 13 et = (EditText) findViewById(R.id.et); 14 15 String inputText = load(); 16 // 17 //if(!(inputText == null || inputText.length() == 0)) 18 //android.text.TextUtils 19 // 20 if(!TextUtils.isEmpty(inputText))//empty 空的 adj 21 { 22 et.setText(inputText); 23 et.setSelection(inputText.length()); 24 Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show(); 25 } 26 27 } 28 29 // 30 //销毁活动时在文件中保存内容 31 // 32 @Override 33 protected void onDestroy() 34 { 35 super.onDestroy(); 36 String inputText = et.getText().toString(); 37 38 save(inputText); 39 } 40 41 // 42 //保存 43 // 44 private void save(String inputText) 45 { 46 BufferedWriter bWriter = null; 47 48 try 49 { 50 bWriter = new BufferedWriter(new OutputStreamWriter(openFileOutput("data", Context.MODE_PRIVATE))); 51 bWriter.write(inputText); 52 } catch (IOException e) 53 { 54 e.printStackTrace(); 55 } finally 56 { 57 if (bWriter != null) 58 { 59 try 60 { 61 bWriter.close(); 62 } catch (IOException e) 63 { 64 e.printStackTrace(); 65 } 66 } 67 } 68 } 69 70 // 71 //读取 72 // 73 private String load() 74 { 75 StringBuffer content = new StringBuffer(); 76 BufferedReader bReader = null; 77 try 78 { 79 bReader = new BufferedReader(new InputStreamReader(openFileInput("data"))); 80 String line = ""; 81 while ((line = bReader.readLine()) != null) 82 { 83 content.append(line); 84 } 85 } catch (IOException e) 86 { 87 e.printStackTrace(); 88 } finally 89 { 90 if(bReader != null) 91 { 92 try 93 { 94 bReader.close(); 95 } catch (IOException e) 96 { 97 // TODO Auto-generated catch block 98 e.printStackTrace(); 99 } 100 } 101 } 102 103 return content.toString(); 104 } 105 }
标签:
原文地址:http://www.cnblogs.com/starman/p/5021654.html