安卓開發:sd卡操作
阿新 • • 發佈:2018-04-17
use AS con AI string extern toast path 沒有
1.向sdcard中寫入數據:
發現向/mnt/sdcard路徑寫數據會報錯,原因:沒有開啟相應權限
解決:配置文件中加入
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
或者:
另外:不建議硬編碼寫成:/mnt/sdcard,應該這樣寫:
String sdPath = Environment.getExternalStorageDirectory().getPath();
在保存數據到sdcard之前,還應該判斷下是否存在sdcard:
if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { String sdPath = Environment.getExternalStorageDirectory() .getPath(); // ...... } else { Toast.makeText(getApplicationContext(),"sd卡不可用", Toast.LENGTH_LONG).show(); }
2.獲取sdcard總大小和可用空間:
File file = Environment.getExternalStorageDirectory(); //總大小 long totalSpace = file.getTotalSpace(); //可用大小 long usableSpace = file.getUsableSpace();//註意返回格式是字節,轉換 String formatTotalSpace = Formatter.formatFileSize(MainActivity.this, totalSpace); String formatUsableSpace = Formatter.formatFileSize(MainActivity.this, usableSpace);
安卓開發:sd卡操作