安卓系統中的檔案讀寫操作
許可權
...
WRITE_EXTERNAL_STORAGE 已經隱含了讀取許可權得到當前應用下的路徑檔案
File file = new File(context.getFilesDir(), filename);
寫檔案
String filename = myfile;String string = Hello world!;FileOutputStream outputStream;try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close();} catch (Exception e) { e.printStackTrace();}
快取檔案
public File getTempFile(Context context, String url) { File file; try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); catch (IOException e) { // Error while creating file } return file;}
SD卡是否可用
/* SD卡是否可寫 */public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false;}/* SD卡是否可讀 */public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false;}
建立檔案
建立一個公用檔案,當程式被卸載時,該檔案依然存在
public File getAlbumStorageDir(String albumName) { //Environment.DIRECTORY_PICTURES為檔案夾名稱,這裡使用的是系統常量 File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e(LOG_TAG, Directory not created); } return file;}
建立一個檔案,當程式被卸載時,該檔案將被刪除
public File getAlbumStorageDir(Context context, String albumName) { //如果沒有適合的子目錄名稱,可以改為調用 getExternalFilesDir() 並傳遞 null。這將返回外部儲存上該應用的專用目錄的根目錄。 File file = new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e(LOG_TAG, Directory not created); } return file;}
諸如 DIRECTORY_PICTURES 的 API 常數提供的目錄名稱非常重要。 這些目錄名稱可確保系統正確處理檔案。 例如,儲存在 DIRECTORY_RINGTONES 中的檔案由系統介質掃描程式歸類為鈴聲,而不是音樂。刪除檔案
常規方法
myFile.delete();
如果檔案儲存在內部儲存中,還可以請求 Context 通過調用 deleteFile() 來定位和刪除檔案:
myContext.deleteFile(fileName);