Android基礎之資料存儲(等待更新…)
1資料存儲方式:
檔案存儲:最為常用,與Java中的I/O完全一樣,可存儲文本、圖檔、音頻等。
SharedPreferences:存儲一些簡單配置,xml格式存儲。
SQLite資料庫:系統自帶輕量級資料庫,支援SQL。
ContentProvider:應用程式之間的資料交換。
網絡存儲:将資料存儲在伺服器上。
1.1檔案存儲(分為内部存儲、外部存儲兩種。)
- 内部存儲:檔案存儲在裝置内部,為應用程式私有,當解除安裝應用程式時随之删除,其他程式通路此檔案時需要提供權限。
将資料存儲到指定檔案:其中:
#1 FileOutputStream fos=openFileOutput(String name, int mode);
是檔案名,
name
是檔案操作模式。
mode
的4種取值模式:
mode
隻能被目前應用程式讀寫、
MODE_PRIVATE
檔案内容可以追加、
MODE_APPEND
可被其他應用程式讀、
MODE_wORLD_READABLE
可被其他應用程式寫。
MODE_WORLD_WRITEABLE
#2 fos.write(content.getBytes());
讀取指定檔案的資料:
#3 fos.close();
其中:
#1 FileInpuStream fis=openFileInput(String name);
是檔案名。
name
其中
#2 byte[] buffer=new byte[fis.available()];
用于擷取檔案長度。
fis.available()
#3 fis.read(buffer);
#4 content=new String(buffer);
#5 fis.close();
- 外部存儲:檔案存儲在SD或者内嵌存儲卡中,為其他應用程式共享,并且可以被浏覽、修改、删除。存儲方式不安全。
#1 擷取外部儲存設備的狀态
String state=Environment.getExternalStorageState();
#2 判斷是否可用,若可用則讀取資料
if (state.equals(Environment.MEDIA_MOUNTED)){
File SDPath=Environment.getExternalStorageDirectory();//擷取SD卡目錄
File file=new File(SDPath,'data.txt');
//存儲資料
FileOutputStream fos;
String data="Hello World";
try{
fos=new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
}catch(Exception e){
e.printStackTrace();
}
//讀取資料
FileInputStream fis;
try{
fis=new FileInputStream(file);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String data=br.readLine();
}catch (Exception e){
e.printStackTrance();
}
}
由于操作SD卡中的資料這一行為需要符合系統安全性,是以需要在清單檔案中添加SD卡讀寫權限。
android.permission.WRITE_EXTERNAL_STORAGE
、
android.permission.READ_EXTERNAL_STORAGE