android筆記

14.3.01


數據存儲(持久化)  

五種:(外存)

1Shared Preferences

Store private primitive data in key-value pairs.

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

2Internal Storage

Store private data on the device memory.

內部存儲

3External Storage

Store public data on the shared external storage.

外部存儲(保存文件、安裝包)

4SQLite Databases

Store structured data in a private database.

數據庫存儲(外存)

5Network Connection

Store data on the web with your own network server.

網絡存儲



1、sharePreferences

應用場景:應用程序有少量的數據需要保存(設置參數的保存)


例子:按鈕點擊保存

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

   SharePreferences preference=getPreferences(0);//0:默認值

//編輯器類型的對象

Editor edit=Preference.edit();

//想編輯器對象添加數據

Edit.putBoolean(isLogin,true);

edit.putString(name,Lucy);

//提交

   Commit();



獲取數據

getBoolean(isLogin,false);//false:默認值

getString(name,SS);//SS:默認值

   privatevoid getData() {

   SharedPreferences preferences = getPreferences(0);

   boolean login = preferences.getBoolean("isLogin", false);

   String name = preferences.getString("name", "Lily");

   mTv_show.setText(login+"  "+name);

}


保存位置

Data/data/包名/shared_prefs/xxx.xml

修改保存位置:

Sharepreferences sp=getSharepreferrences(xibo,0);//xibo保存的文件名





2、InternalStorage

保存位置:

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

保存


privatevoid saveData() {

FileOutputStream openFileOutput =null;

try {

openFileOutput = openFileOutput("aa.txt", MODE_PRIVATE);

String str="Hello";

openFileOutput.write(str.getBytes());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(openFileOutput!=null){

try {

openFileOutput.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}



讀取

FileInputStream

privatevoid getData() {

FileInputStream fis=null;

ByteArrayBuffer bab=new ByteArrayBuffer(4000);

try {

Log.e("getData", "sss");

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

int len;

byte[] buffer=newbyte[1024];

while(-1!=(len=fis.read(buffer))){

bab.append(buffer, 0, len);

}

String str=new String(bab.toByteArray(), 0, bab.length());

mTv_show.setText(str);  

Log.e("getData------>", ""+bab.length());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(fis!=null){

try {

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}


讀寫模式:

MODE_PRIVATE私有模式:只有當前應用才能對這個文件進行讀寫操作,不會進 行疊加,每次都清空

MODE_APPEND添加模式:只有當前應用才能對這個文件進行讀寫操作,對數據  追加

MODE_WORLD_READABLE其他應用可讀

MODE_WORLD_WRITEABLE其他應用可寫


3、外部讀取


查找sd

   File file =Environment.getExternalStorageDirectory();

   String path=file.getAbsolutePath();

判斷sd卡是否可用

Environment..MEDIA_MOUNTED.equals(Environment.getExternalStorageState());

獲得sd卡的可用空間

file.getFreeSpace();


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章