一、讀取檔案
1.讀取檔案
- 我們的APP在重新啟動程式的時候EditText能夠從系統中獲取資料,修改
MainActivity中的代碼
public class MainActivity extends Activity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
...........................
String inputText = load();
if(!TextUtils.isEmpty(inputText)) {
edit.setText(inputText);
edit.setSelection(inputText.length());
Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
}
}
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(Exception e) {
e.printStackTrace();
}
}
}
return content.toString();
}
...............................
- 編輯一個load方法,用于讀取app記憶體儲的資料,如果讀到的內容不為空,就呼叫setText方法,把內容放到EditText中,然后呼叫setSelection方法將輸入的游標移動到文本的末尾位置以便于再次輸入,然后彈出一個“還原成功”,
- 注意:判斷字串非空的時候使用了TextUtils.isEmpty()方法,這個方法同時對null和空字串都進行了判斷


- 輸入一段文字之后,然后點擊退出鍵,再進入這個APP的時候,就會把之前的內容填充進去,
- 該方法不適合存盤復雜的資料,因此我們看一下另一種方法,
二、SharedPreference存盤
- SharedPreferece使用鍵值對進行存盤資料,
1.使用方法
- 獲取SharedPreference物件,android提供了三種方法
- Context類中的getSharedPreference方法
- 該類接收兩個引數,第一個是指定SharedPreference檔案的名稱,檔案存放于
/data/data/<packagename>/shared_prefs/目錄下;第二個引數用于指定操作模式,主要由兩種模式可以選,MODE_PRIVATE和MODE_PROCESS,第一個是默認操作,和傳入0差不多,表示只有當前程式可以對這個SharedPreferece檔案進行讀寫,第二個一般用于會有多個行程中對同一個SharedPreference檔案進行讀寫的情況,
- 該類接收兩個引數,第一個是指定SharedPreference檔案的名稱,檔案存放于
- Context類中的getSharedPreference方法
三、原始碼:
- FilePersistenceTest
- 地址:https://github.com/ruigege66/Android/tree/master/FilePersistenceTest
- CSDN:https://blog.csdn.net/weixin_44630050
- 博客園:https://www.cnblogs.com/ruigege0000/
- 歡迎關注微信公眾號:傅里葉變換,個人賬號,僅用于技術交流
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/106750.html
標籤:其他
上一篇:Sagit.Framework For IOS 開發框架入門教程14:STLocation 獲取GPS坐標資訊、跳轉第三方地圖
