1.檔案儲存體在手機再帶的儲存空間
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 儲存內容,註:允許其他應用對該檔案讀和寫
* @param filename 檔案名稱
* @param content 檔案內容
* @throws Exception
*/
public void saveRW(String filename, String content) throws Exception{
FileOutputStream outStream = context.openFileOutput(filename,
Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 讀取檔案內容
* @param filename 檔案名稱
* @return
* @throws Exception
*/
public String readFile(String filename) throws Exception{
FileInputStream inStream = context.openFileInput(filename);
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while( (len = inStream.read(buffer))!= -1){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();//得到檔案的位元據
outStream.close();
inStream.close();
return new String(data);
}
檔案的操作模式:Context.MODE_PRIVATE 為預設的操作模式,代表該檔案私人,只能被應用本身使用,覆蓋源檔案
Context.APPEND 為追加模式,私人的。存在就往檔案追加內容
Context.MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取
Context.MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入
如果希望檔案被其他應用讀和寫,可以傳入:
openFileOutput("zhgang.txt",Context.MODE_WORLD_READABLE+
Context.MODE_WORLD_WRITEABLE);
android有一套自己的安全模型,當應用程式(.apk)在安裝時系統就會分配給他一個userid,當該應用要去訪問其他資源比如檔案的時候
就需要userid匹配。預設情況下,任何應用建立檔案,sharedprefernces,資料庫都應該是私人的(位於/data/data/<package name>/files),
其他程式無法訪問,除非在建立時指定了Context.MODE_WORLD_READABLE,Context.MODE_WORLD_WRITEABLE,只有這樣其他程式才能正確訪問
2>檔案儲存體在SDCARD
android2.2 /mnt/sdcard
<2.2 /sdcard
在SDCARD加許可權
<!-- 在SDCard中建立與刪除檔案許可權 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard寫入資料許可權 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
/** www.2cto.com
* 以私人檔案儲存內容
* @param filename 檔案名稱
* @param content 檔案內容
* @throws Exception
*/
public void saveToSDCard(String filename, String content) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(content.getBytes());
outStream.close();
}
//判斷sdcard是否存在於手機上,並且可以進行讀寫訪問
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
fileService.saveToSDCard(filename, content);
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}else{
Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
}
作者:get123