天天看點

資料存儲(持久化)

14.3.01

資料存儲(持久化)  

五種:(外存)

1、shared preferences

store private primitive data in key-value pairs.

參數共享(儲存關鍵參數:下載下傳、登陸等)

2、internal storage

store private data on the device memory.

内部存儲

3、external storage

store public data on the shared external storage.

外部存儲(儲存檔案、安裝包)

4、sqlite databases

store structured data in a private database.

資料庫存儲(外存)

5、network connection

store data on the web with your own network server.

網絡存儲

1、sharepreferences

應用場景:應用程式有少量的資料需要儲存(設定參數的儲存)

例子:按鈕點選儲存

//得到參數共享類型的對象

   sharepreferences preference=getpreferences(0);//0:預設值

//編輯器類型的對象

editor edit=preference.edit();

//想編輯器對象添加資料

edit.putboolean(“name”);

//送出

   commit();

擷取資料

getboolean(“name”);//ss:預設值

   sharedpreferences preferences = getpreferences(0);

   string name = preferences.getstring("name", "lily");

}

儲存位置

data/data/包名“xibo<span style=\"\\"font-size:14px;font-family:'times\">”,0);//xibo儲存的檔案名

2、internalstorage

儲存位置:

data/data/包名/files/aa.txt"

儲存

fileoutputstream openfileoutput =null;

openfileoutput = openfileoutput("aa.txt", mode_private);

openfileoutput.write(str.getbytes());

e.printstacktrace();

if(openfileoutput!=null){

openfileoutput.close();

讀取

fileinputstream

fileinputstream fis=null;

try {

fis=new fileinputstream("data/data/com.example.day_example/files/aa.txt");

byte[] buffer=newbyte[1024];

bab.append(buffer, 0, len);

string str=new string(bab.tobytearray(), 0, bab.length());

log.e("getdata------>", ""+bab.length());

if(fis!=null){

fis.close();

讀寫模式:

mode_private私有模式:隻有目前應用才能對這個檔案進行讀寫操作,不會進 行疊加,每次都清空

mode_append添加模式:隻有目前應用才能對這個檔案進行讀寫操作,對資料  追加

mode_world_readable其他應用可讀

mode_world_writeable其他應用可寫

3、外部讀取

查找sd卡是否可用

environment..media_mounted.equals(environment.getexternalstoragestate());

獲得