安卓系統中的檔案讀寫操作

來源:互聯網
上載者:User

安卓系統中的檔案讀寫操作
許可權

        ...
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);
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.