Ways to manipulate folders and files in SD cards _android

Source: Internet
Author: User

Creating a Folder

Copy Code code as follows:

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, you will report the following error:

ApplicationContext Unable to create external files directory

It is recommended that you create a folder using Mkdirs () instead of mkdir (), because the former can create the parent folder at the same time, if it does not, the latter cannot.

Creation of files

Copy Code code as follows:

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 you create cannot have a. suffix, or you will report the following error:

Java.io.filenotfoundexception:/mnt/sdcard/pic/pic.png (is directory)

Also, it is a good idea to add the following permissions when reading and writing to a folder:

Copy Code code as follows:

<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.