資料存放區與訪問常用方式: 檔案 SharedPreferences(偏好參數設定) SQLite資料庫 內容提供者(Content provider) 網路 Activity(Context) Context.getCacheDir()方法用於擷取/data/data/<package name>/cache目錄 Context.getFilesDir()方法用於擷取/data/data/<package name>/files目錄 Activity(Context)提供了openFileOutput(filename,mode)方法用於把資料輸出到檔案中; 第一個參數用於指定檔案名稱,不能包含路徑分隔字元‘/' 第二個參數為操作模式: Context.MODE_PRIVATE:私人操作模式建立出來的檔案只能被本程式訪問,如果檔案不存在,會自動建立,另外:寫入檔案中的內容會覆蓋原檔案的內容; Context.MODE_APPEND:模式會檢查檔案是否存在,如果存在則會追加內容,否則建立新檔案; Context.MODE_READABLE:表示當前檔案可以被其它應用讀取; Context.MODE_WRITEABLE:表示當前檔案可以被其它應用寫入; 如果希望檔案被其它應用讀和寫:傳入(Context.MODE_READABLE+Context.MODE_WRITEABLE) FileOutputStream outStream = context.openFileOutput(filename,Context.MODE_PRIVATE); 例子 //寫資料 public void writeFile(String fileName,String writestr{ try{ FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE); byte [] bytes = writestr.getBytes(); fout.write(bytes); fout.close(); } catch(Exception e){ e.printStackTrace(); } } //讀資料 public String readFile(String fileName){ String res=""; try{ FileInputStream fin = openFileInput(fileName); int length = fin.available(); byte [] buffer = new byte[length]; fin.read(buffer); res = EncodingUtils.getString(buffer, "UTF-8"); fin.close(); } catch(Exception e){ e.printStackTrace(); } return res; } //param 檔案名稱,操作方式 android有一套自己的安全模型,當應用程式(.apk)在安裝時系統會分配給一個userid,當該應用去訪問其它資源如檔案的時候,會進行 userid的匹配,預設情況下任何應用建立的檔案,sharedpreferences,資料庫都是私人的(建立的檔案儲存在/data/data /<package name>/files目錄下),只有指定操作模式為外部可讀或寫才可以被其它程式訪問; 讀取檔案: <1> FileInputStream inStream = context.openFileInput(filename); Log.i(TAG,inStream....) <2> path="/data/data/<package name>/files/hello.txt"; File file = new File(path); FileInputStream inStream = new FileInputStream(file); Log.i(TAG,inStream....) ctrl + shift + x/y 大小寫 從resource的raw中讀取檔案資料: String res = ""; try{ //得到資源中的Raw資料流 InputStream in = getResources().openRawResource(R.raw.test); //得到資料的大小 int length = in.available(); byte [] buffer = new byte[length]; //讀取資料 in.read(buffer); //依test.txt的編碼類別型選擇合適的編碼,如果不調整會亂碼 res = EncodingUtils.getString(buffer, "BIG5"); //關閉 in.close(); }catch(Exception e){ e.printStackTrace(); } |