操作SD卡中文件夾和文件的方法
文件夾的創(chuàng)建
File file = Environment.getExternalStorageDirectory();
File file_0 = new File(file, "file_demo");
if (!file_0.exists()) {
file_0.mkdirs();
}
創(chuàng)建文件夾的時候,需要<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />權(quán)限,
否則會報如下錯誤:
ApplicationContext Unable to create external files directory
這里建議使用mkdirs()創(chuàng)建文件夾,而不是用mkdir(),因為前者可以同時創(chuàng)建父文件夾,如果不存在的話,而后者不能。
文件的創(chuàng)建
File file = Environment.getExternalStorageDirectory();
File file_0 = new File(file, "pic");
if (!file_0.exists()) {
file_0.mkdirs();
}
try {
File pic = new File(file_0, "pic.png");
InputStream is = getResources().openRawResource(
R.drawable.ic_launcher);
OutputStream os = new FileOutputStream(pic);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
創(chuàng)建的文件名不能帶有.后綴的,否則會報如下錯誤:
java.io.FileNotFoundException:/mnt/sdcard/pic/pic.png (Is a directory)
同時在對文件夾的讀寫操作時最好添加如下權(quán)限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
相關(guān)文章
android開發(fā)中ListView與Adapter使用要點介紹
項目用到ListView,由于要用到 ImageView ,圖片源不是在資源里面的,沒法使用資源 ID,因此無法直接使用SimpleAdapter,要自己寫一個Adapter。 在使用ListView和Adapter需要注意以下幾點2013-06-06
Android 中自定義ContentProvider與ContentObserver的使用簡單實例
這篇文章主要介紹了Android 中自定義ContentProvider與ContentObserver的使用簡單實例的相關(guān)資料,這里提供實例幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-09-09
Android通過應(yīng)用程序創(chuàng)建快捷方式的方法
這篇文章主要介紹了Android通過應(yīng)用程序創(chuàng)建快捷方式的方法,涉及Android基于應(yīng)用程序創(chuàng)建快捷方式的圖標(biāo)及動作等技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09

