[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

在開發App過程中常常遇到需要保存Device端資訊的狀況,最常見的就是使用者設定或是遊戲的進度…等。Android SDK提供了很多方法來進行資料儲存,包含了:Shared Preferences、Internal Storage、External Storage、SQLite與Network。

Shared Preferences提供了Key-pair的儲存型式,可以寫入primitive type資料;Internal、External Storage則將資料寫入Device端的內(外)部儲存體;SQLite是以local端小型資料庫型式儲存資料,可以使用一般資料庫query的方式取得資料;最後是Network則是將資料儲存在遠端,需要時再以Network connection取得。本文將針對Internal Storage的檔案系統使用進行說明:


Internal Storage

當你使用Internal Storage存取File時,檔案會直接寫入Device的內部儲存體,路徑將是對應Application的一個私有資料夾(Private folder),只有該Application才可以存取它,其它應用程式沒有存取裡面檔案的權限,而這些檔案會隨著應用程式從系統移除而一併被刪除。

存取資料夾(Access Directory) :getDir()

如果想在Internal Storage裡存取或建立資料夾,就必須使用getDir(String DirName, int model),系統會根據輸入的DirName參數來判斷該Directory是否存在,不存在就建立一個該名字的資料夾
String fileName = "test";
getDir(fileName, Context.MODE_PRIVATE);
寫入資料(write file to internal storage):write()

要寫入檔案至internal storage,先呼叫openFileOutput(FileName)取得取得該檔案的FileOutputStream,再將要寫入的資料傳入write()並記得在寫入完成後呼叫close()將output stream關閉。
String fileName = "test";
FileOutputStream writer = openFileOutput(fileName, Context.MODE_PRIVATE);
writer.write(content.getBytes());
writer.close();

讀取資料(read file from internal storage):read()

要讀取internal storage的檔案,使用openFileInput(FileName)取得取得該檔案的FileInputStream,再使用read()讀取資料input,讀取完畢後同樣以close()關閉資料流。
//取得檔名
String fileName = "test";
int readed; //已讀取的位元數
String content=""; //內容
byte[] buff = new byte[256]; //input stream buffer
//Input stream
try{
 FileInputStream reader = openFileInput(fileName);
 while((readed = reader.read(buff))!=-1){
  content+=new String(buff).trim();
 }
}catch(FileNotFoundException e){
 e.printStackTrace();
}catch (IOException e){
 e.printStackTrace();
}

留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

【海外婚紗】造型篇-我的超人新祕Sunny-Yang