Android development-operations on files on the SD card are carried from the Network)

Source: Internet
Author: User

1. Get the directory of the storage device:/sdcard (generally)



Sdpath = environment. getexternalstoragedirectory () + "/";


2. Determine whether the folder on the SD card exists: Use the exists () method of the file object.


/**

* Determine whether a file already exists;

*

/

Public Boolean checkfileexists (string filepath ){

File file = new file (sdpath + filepath );

Return file. exists ();

}


3. Create a directory on the SD card: Use the mkdir () method of the file object.


/*

* Create a directory on the SD card;

*/

Public file createdir (string dirpath ){

File dir = new file (sdpath + dirpath );

Dir. mkdir ();

Return dir;

}


4. Create a file on the SD card: Use the createnewfile () method of the file object.

/*

* Create a file on the SD card;

*/

Public file createfile (string filepath) throws ioexception {

File file = new file (sdpath + filepath );

File. createnewfile ();

Return file;

}

5. Write the inputstream byte stream to the SD card file.

/**

* Write data from an inputstream to the SD card.

*/

Public file writestreamtosdcard (string dirpath, string filename, inputstream input ){

File file = NULL;

Outputstream output = NULL;

Try {

// Create a directory;

Createdir (dirpath );

// Create a file in the Created directory;

File = createfile (dirpath + filename );

Output = new fileoutputstream (File );

Byte [] bt = new byte [4*1024];

While (input. Read (BT )! =-1 ){

Output. Write (BT );

}

// Refresh the cache,

Output. Flush ();

} Catch (ioexception e ){

E. printstacktrace ();

}

Finally {


Try {

Output. Close ();

}

Catch (exception e ){

E. printstacktrace ();

}

}


Return file;


}


6. Access Permissions:

Add the following to androidmanifest:

<Uses-Permission Android: Name = "android. Permission. Internet"> </uses-Permission>

<Uses-Permission Android: Name = "android. Permission. write_external_storage"> </uses-Permission>

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.