標籤:
什麼叫資料持久化
資料持久化就是指將那些記憶體中的瞬時資料儲存到存放裝置,裝置可以是本機、資料庫等。Android 系統中主要提供了三種方式用於簡單地實現資料持久化功能,即檔案儲存體、SharedPreference 儲存以及資料庫儲存。
持久化操作
- 檔案儲存
( 1 ) 寫入檔案
Context 類中提供了一個 openFileOutput ()方法,這個方法返回一個FileOutputStream對象。這個方法接收2個參數,第一個參數是檔案名稱,這裡的檔案名稱不能包括路徑,安卓中所有的檔案都預設儲存在/data/data/<packagename>/files/目錄下的,第二個參數是檔案的操作模式,主要有2種,MODE_PRIVATE 和 MODE_APPEND,MODE_PRIVATE是預設的模式,寫入的內容會直接覆蓋源檔案中的內容; MODE_APPEND模式下如果該檔案已經存在,那麼直接往檔案裡面追加內容,不存在就建立檔案。
將常值內容儲存到檔案樣本:
public void save() { String data = "Data to save"; FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } }}
我們先通過openFileOutput()獲得一個FileOutputStream對象,然後使用FileOutputStream對象構建一個OutputStreamWriter對象,可以讓位元組流轉化為字元流,然後使用OutputStreamWriter對象構建BufferedWriter獲得BufferedWriter對象,這個對應的流使用了緩衝,能夠提高輸出效率,調用BufferedWriter的write方法寫入資料。
( 2 ) 讀取檔案
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();}
對於檔案的讀取Context類提供了openFileInput()方法,擷取一個FileInputStream對象,然後使用InputStreamReader構建得到一個InputStreamReader對象,把位元組流轉化為字元流。然後構建出BufferedReader對象。然後我們把讀取的內容放到StringBuilder中,最後調用toString()方法返回資料。
未完。
安卓學習之持久化