天天看點

Android使用檔案存儲資料

應用場景:離開登入頁面儲存賬号

1、在onCreate方法中提取儲存資料,即給賬号輸入框指派

etPhone.setText(DataUtils.loadData(this));
           

2、在onDestroy方法中儲存賬号

String phone = etPhone.getText().toString();
DataUtils.saveData(this, phone);
           

3、工具類(資料儲存方法和提取方法)

public class DataUtils {

    /**
     * 儲存資料
     * @param context
     * @param str
     */
    public static void saveData(Context context, String str) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = context.openFileOutput("phone", Context.MODE_PRIVATE);//phone:檔案名;MODE_PRIVATE:同檔案名覆寫;MODE_APPEND:同檔案名添加
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(str);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                if (writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 提取資料
     * @param context
     */
    public static String loadData(Context context) {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder str = new StringBuilder();
        try {
            in = context.openFileInput("phone");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null){
                str.append(line);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                if (reader != null){
                    reader.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return str.toString();
    }
}
           

        上面單個字段的存儲一般使用SharedPreferences來儲存資料,這種檔案存儲可以适用于網絡json資料的本地儲存,送出表單資料的臨時儲存等。

繼續閱讀