14.3.01
數據存儲(持久化)
五種:(外存)
Store private primitive data in key-value pairs.
參數共享(保存關鍵參數:下載、登陸等)
Store private data on the device memory.
內部存儲
Store public data on the shared external storage.
外部存儲(保存文件、安裝包)
Store structured data in a private database.
數據庫存儲(外存)
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();
e.printStackTrace();
if(openFileOutput!=null){
openFileOutput.close();
e.printStackTrace();
}
}
讀取
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());
e.printStackTrace();
e.printStackTrace();
if(fis!=null){
fis.close();
e.printStackTrace();
}
}
讀寫模式:
MODE_PRIVATE私有模式:只有當前應用才能對這個文件進行讀寫操作,不會進 行疊加,每次都清空
MODE_APPEND添加模式:只有當前應用才能對這個文件進行讀寫操作,對數據 追加
MODE_WORLD_READABLE其他應用可讀
MODE_WORLD_WRITEABLE其他應用可寫
3、外部讀取
查找sd卡是否可用
Environment..MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
獲得