Methods to manipulate folders and files on the SD card
- 2020-05-09 19:19:24
- OfStack
Folder creation
File file = Environment.getExternalStorageDirectory();
File file_0 = new File(file, "file_demo");
if (!file_0.exists()) {
file_0.mkdirs();
}
When you create a folder, you need to < uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" / > Permissions,
Otherwise, the following error will be reported:
ApplicationContext Unable to create external files directory
It is recommended to use mkdirs () to create a folder, rather than mkdir (), because the former can create a parent folder at the same time, if it does not exist, while the latter cannot.
File creation
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();
}
The file name created cannot have the. Suffix, otherwise the following error will be reported:
java.io.FileNotFoundException:/mnt/sdcard/pic/pic.png (Is a directory)
At the same time, it is better to add the following permissions when reading and writing to the folder:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />