1. 程式人生 > >第一行程式碼 第六章 資料儲存方案

第一行程式碼 第六章 資料儲存方案

Android主要提供了3個方法實現資料的持久化功能
1、SharedPreference儲存;2、檔案儲存;3、資料庫儲存

1、檔案儲存
它是android中最基本的一種資料儲存方式。它不對儲存的內容做任何的格式化處理,將資料原封不動地儲存到檔案中。

Context類中提供了openFileOutput()方法,用於將資料儲存到指定的檔案中。
該方法提供兩個接收引數
第一個引數是檔名。這裡指定的檔名不可以包含路徑,因為所有的檔案都預設儲存到/data/data//file目錄下。
第二個引數是檔案的操作模式。提供兩種模式:
1.MODE_PRIVATE:當指定同樣檔名時,所寫入的內容將會覆蓋原檔案的內容
2.MODE_APPEND:如果該檔案已經存在,則在檔案的末尾追加內容。

該方法返回一個FileOutputStream物件,得到這個物件之後,就可以使用Java流的方式將資料寫入到檔案中。
Java流方式:寫入資料
1.通過openFileOutput()方法得到FileOutputStream物件;
2.藉助FileOutputStream物件,構建一個OutputStreamWriter物件;
3.藉助OutputStreamWriter物件,構建一個BufferedWriter物件
4.通過BufferedWriter物件提供的write()方法,就可以將文字內容寫入到檔案中。

例項:如何將一段文字內容儲存到檔案中

public void
saveFile(){ String data = "Hello World!"; FileOutputStream mFileOutputStream = null; OutputStreamWriter mOutputStreamWriter = null; BufferedWriter writer = null; try{ mFileOutputStream = openFileOutput("data.txt", MODE_APPEND); mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream) writer = new
BufferedWrite(mOutputStreamWriter); writer.write(data); }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(writer != null){ writer.close(); } }catch(IOException e){ e.printStackTrace(); } } }

Context類還提供了一個openFileInput()方法,用於從檔案中讀取資料。
它只接收一個引數,即檔名

它返回一個FileInputStream物件,得到這個物件後就可以通過Java流的方式將資料讀出來
Java流的方式:讀取資料
1.通過openFileInput方法得到一個FileInputStream物件;
2.藉助FileInputStream物件,構建InputStreamReader物件;
3.藉助InputStreamReader物件,構建BufferedReader物件
4.通過BufferedReader進行一行一行地讀取,並存放到StringBuilder物件中。

例項:如何從檔案中讀取文字資料

public String load(){
    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuilder builder = new StringBuidler();
    try{
        fileInputStream = openFileInput("data.txt");
        inputStreamReader = new InputStreamReader(fileInputStream);
        reader = new BufferedReader(inputStreamReader);
        String line = "";
        while((line=reader.readLine()) != null){
            builder.append(line);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(reader != null){
            try{
            reader.close();
            }catch(IOException e){
                e.printStackTrace();
            }

        }
    }

    return builder.toString();
}

例項:讀寫檔案
MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnWriteToFile;
    private Button btnReadFromFile;
    private EditText etIput;
    private TextView tvShowContent;

    private final  static String FILE_NAME = "data.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnWriteToFile = (Button)findViewById(R.id.btnWriteToFile);
        btnReadFromFile = (Button)findViewById(R.id.btnReadFromFile);
        etIput = (EditText)findViewById(R.id.etIput);
        tvShowContent = (TextView)findViewById(R.id.tvShowContent);

        btnWriteToFile.setOnClickListener(this);
        btnReadFromFile.setOnClickListener(this);

        String data = readFromFile(FILE_NAME);
        if(!TextUtils.isEmpty(data)){
            etIput.setText(data);
            etIput.setSelection(data.length());
            tvShowContent.setText(data);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnWriteToFile:
                String content = etIput.getText().toString();
                writeToFile(FILE_NAME, content);
                break;
            case R.id.btnReadFromFile:
                String ret = readFromFile(FILE_NAME);
                tvShowContent.setText(ret);
                break;
            default:break;
        }
    }

    private void writeToFile(String filename, String content) {
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        BufferedWriter writer = null;
        try {
            fileOutputStream = openFileOutput("data.txt", MODE_APPEND);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            writer = new BufferedWriter(outputStreamWriter);
            writer.write(content);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    private String readFromFile(String filename){
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try{
            fileInputStream = openFileInput(filename);
            inputStreamReader = new InputStreamReader(fileInputStream);
            reader = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = reader.readLine()) != null){
                builder.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return builder.toString();
    }
}

相關推薦

第一程式碼 資料儲存方案

Android主要提供了3個方法實現資料的持久化功能 1、SharedPreference儲存;2、檔案儲存;3、資料庫儲存 1、檔案儲存 它是android中最基本的一種資料儲存方式。它不對儲存的內容做任何的格式化處理,將資料原封不動地儲存到檔案中。

第一程式碼——資料儲存方案——詳解持久化技術

目錄: 6.1 持久化技術簡介 6.2 檔案儲存 6.2.1 將資料儲存到檔案中 6.2.2 從檔案中讀出資料 6.3 SharedPreferences 儲存 6.3.1 將資料儲存到SharedPreferences中 6.3.2 從SharedPreferenc

第二程式碼學習筆記——:資料儲存方案——詳解持久化技術

本章要點 任何一個應用程式,總是不停的和資料打交道。 瞬時資料:指儲存在記憶體當中,有可能因為程式關閉或其他原因導致記憶體被回收而丟失的資料。 資料持久化技術,為了解決關鍵性資料的丟失。 6.1 持久化技術簡介 資料持久化技術:指那些記憶體中的瞬時

第一程式碼——:跨程式共享資料——探究內容提供器

目錄: 7.1 內容提供器簡介 7.2 執行時許可權 7.2.1 Android 許可權機制詳解 7.2.2 在程式執行時中申請許可權 7.3 訪問其他程式中的資料 7.3.1 ContentResolver的基本用法 7.3.2 讀取系統聯絡人 7.4 建立自己

第一程式碼---使用網路技術

這一章的內容主要有使用WebView展示網頁,使用HTTP協議訪問網路,解析xml資料以及解析json資料,下面是我自己的總結: WebView 在應用程式裡展示網頁 簡單用法 WebView webview=(Webview)findViewById(R.id.web

第一程式碼——十三:繼續進階——你還應該掌握的高階技巧

目錄: 13.1 全域性獲取 Context的技巧 13.2 使用 Intent傳遞物件 13.2.1 Serializable 方式 13.2.2 Parcelable 方式 13.3 定製自己的日誌工具 13.4 除錯Android 程式 13.5 建立定時任務

第一程式碼——:後臺默默的勞動者——探究服務

目錄: 10.1 服務是什麼 10.2 Android 多執行緒程式設計 10.2.1 執行緒的基本用法 10.2.2 在子執行緒中更新UI 10.2.3 解析非同步訊息處理機制 10.2.4 使用AsyncTask 10.3 服務的基本用法 10.3.1 定義一

第一程式碼——:看看精彩的世界——使用網路技術

目錄: 9.1 WebView的用法 9.2 使用HTTP協議訪問網路 9.2.1 使用HttpURLConnection 9.2.2 使用OkHttp 9.3 解析XML格式資料 9.3.1 Pull解析方式 9.3.2 SAX解析方式 9.4 解析JSON格式

第一程式碼——:豐富你的程式——運用手機多媒體

目錄: 8.1 將程式執行到手機上 8.2 使用通知 8.2.1 通知的基本用法 8.2.2 通知的進階技巧 8.2.3 通知的高階功能 8.3 呼叫攝像頭和相簿 8.3.1 呼叫攝像頭拍照 8.3.2 從相簿中選擇照片 8.4 播放多媒體檔案 8.4.1

第一程式碼——:全域性大喇叭——詳解廣播機制

目錄: 5.1 廣播機制簡介 5.2 接收系統廣播 5.2.1 動態註冊監聽網路變化 5.2.2 靜態註冊實現開機啟動 5.3 傳送自定義廣播 5.3.1 傳送標準廣播 5.3.2 傳送有序廣播 5.4 使用本地廣播 5.5 廣播最佳實踐——實現強制下線功能

第一程式碼——:手機平板要兼顧——探究碎片

目錄: 4.1 碎片是什麼 4.2 碎片的使用方式 4.2.1 碎片的簡單用法 4.2.2 動態新增碎片 4.2.3 在碎片中模擬返回棧 4.2.4 碎片和活動之間進行通訊 4.3 碎片的生命週期 4.3.1 碎片的狀態和回撥 4.3.2 體驗碎片的生命週期

第一程式碼——:軟體也要拼臉蛋——UI開發的點點滴滴

目錄: 3.1 如何編寫程式介面 3.2 常用控制元件的使用方法 3.2.1TextView 3.2.2 Button 3.2.3 EditText 3.2.4 ImageView 3.2.5 ProgressBar 3.2.6 Al

程式碼5 資料儲存

5.1.2 json import json info = { 'name': '王偉', 'gender': '難', 'birthday': '1992-10-08' } with open('512.json','w', encod

第一程式碼——十二:最佳的UI體驗——Material Design實戰

目錄: 12.1 什麼是 Material Design 12.2 Toolbar 12.3 滑動選單 12.3.1 DrawerLayout 12.3.2 NavigationView 12.4 懸浮按鈕和可互動提示 12.4.1 FloatingActionBut

第一程式碼——十一:Android特色開發——基於位置的服務

目錄: 11.1 基於位置的服務簡介 11.2 申請API Key 11.3 使用百度定位 11.3.1 準備LBS SDK 11.3.2 確定自己位置的經緯度 11.3.3 選擇定位模式 11.3.4 看得懂的位置資訊 11.4 使用百度地圖 11.4.1

資料探勘建模過程

資料預處理 資料讀寫 JSON 資料結構 import json匯入json包。json.loads(josn格式的物件) 返回一個字典 ,json.load(檔名)讀取檔案.json.dumps(josn格式的物件)寫成字串,json.dump(josn格式的物件,檔名)

【資料庫視訊】 資料查詢和管理

一、簡單的SELECT語句 語法格式: SELECT [ALL|DISTINCT] select_list [INTO new_table] FROM table_source [WHERE search_conditions] [GROUP

SQL儲存過程)

1、儲存過程的優點 ①允許模組化程式設計 ②執行速度更快 ③減少網路流通量 ④提高系統安全性 2、儲存過程的分類 ①系統儲存過程 ②使用者自定義儲存過程 3、常用的系統儲存過程 4、使用儲存過程 ①定義儲存過程分語法         cr

演算法競賽入門經典: 資料結構基礎 6.1卡片遊戲

/* 卡片遊戲: 桌上有一疊拍,從第一張牌(位於頂面的牌)開始從上往下依次編號為1~n。當至少還剩兩張牌時進行以下操作:把第一張牌扔掉,然後把新的第一張放到整疊牌 的最後。輸入n,輸出每次扔掉的牌,以及最後剩下的牌 思路: 設定剪枝陣列,凡是扔掉的牌,置剪枝標記為真,迴圈

第一程式碼系列第二——更多隱式Intent用法(開啟網頁)

效果圖 修改FirstActivity中按鈕事件 Button button1 = (Button) findViewById(R.id.button_1); button1.setOnClickListener(new OnClickListener() {