Android storage learning: Reading and Writing files in External Storage

Source: Internet
Author: User

Android storage learning: Reading and Writing files in External Storage

This section describes how to read and write files in the internal storage of a mobile phone. That is how to read and write files in Sdcard.

The previous logon interface is used as an example to illustrate how to read and write files in the internal storage of Android storage)

First, we will display the written code:

When the click-through confirmation and automatic hooks are selected, an info.txt file will be created in the sdcard folder.

 

Public void login (View v) {String name = ed_nam.getText (). toString (); String passwd = ed_passwd.getText (). toString (); // determines whether the user name or password is input if (name. equals () | (passwd. equals () {Toast. makeText (this, the user name or password cannot be blank, Toast. LENGTH_SHORT ). show ();} else {// if Automatic Logon is selected, we need to save the username and password if (cb. isChecked () {// create a File. The user saves the user name and password file = new File (sdcard/info.txt); try {FileOutputStream fos = new FileOutputStream (file ); // write the user name and password, and write the fos in name # passwd format. write (name ##+ passwd ). getBytes (); // close the output stream fos. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} Toast. makeText (this, logon successful, Toast. LENGTH_SHORT ). show ();}}}

 

After the command is executed, the result is as follows:

Similarly, you can change the path read in the previous section to the path of sdcard:

 

Public void readInfo () {File file = new File (sdcard/info.txt); // if the file exists, read if (File. exists () {try {FileInputStream fin = new FileInputStream (file); // convert bytes into bytes stream BufferedReader buffer = new BufferedReader (new InputStreamReader (fin )); // read the username and password in the file String text = buffer. readLine (); // String s [] = text. split (#); // set it to EditTexted_nam.setText (s [0]); ed_passwd.setText (s [1]);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

Of course, we can see that. The above Sdcard writing paths are incorrect, and the program's robustness is not very high, so we should use the API provided by Google to access sdcard: getExternalStorageDirectory

 

 

// Create a File and save the user name and password. // file File = new File (sdcard/info.txt); file File = new File (Environment. getExternalStorageDirectory (), info.txt );
Imagine that when we write a file to sdcard, but due to limited sdcard capacity, we are not enough to put it down, so when the user wants to put a file into the sdcard, you must first judge whether the bucket is not satisfied. If the bucket is not satisfied, please give a reminder.

 

Then how to get the current available capacity of the sdcard:

// Determine whether the File size exceeds the size of the sdcard public Boolean sdcardAvailable (int size) {file File = Environment. getExternalStorageDirectory (); StatFs stat = new StatFs (file. getPath (); // the size of each block long blockSize = stat. getBlockSize (); // The number of public blocks long totalBlocks = stat. getBlockCount (); // The total amount of available space, in bytes long availableBlocks = stat. getAvailableBlocks (); if (availableBlocks> size) {return true;} return false ;}


 

When writing a file, you can first compare it with the available space of sdcard:

 

 

Try {FileOutputStream fos = new FileOutputStream (file); // write the username and password, and write the data in name # passwd format // The length of the data to be written, the Unit is byte int len = (name ##+ passwd ). getBytes (). length/8; if (sdcardAvailable (len) {fos. write (name ##+ passwd ). getBytes ();} else {Toast. makeText (this, sdcard insufficient storage space, Toast. LENGTH_SHORT ). show () ;}// close the output stream fos. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}

In this way, the file size is not large and the write capacity is insufficient in half.

 

 

Another scenario is that when we suddenly write content to the sdcard, if the sdcard has some problems and is not mounted, it cannot be written. Therefore, before reading and writing, you must determine whether the sdcard is running normally.

 

If (cb. isChecked () {// create a File. Save the user name and password. // file File = new File (sdcard/info.txt);/* MEDIA_CHECKING: the SD card is preparing * MEDIA_MOUNTED: the SD card has been mounted and is being read/written to * MEDIA_REMOVED: No SD card * MEDIA_UNKNOWN: the SD card * MEDIA_UNMOUNTED: the SD card exists, but not mounted **/if (Environment. getExternalStorageDirectory (). equals (Environment. MEDIA_MOUNTED) {File file = new File (Environment. getExternalStorageDirectory (), info2.txt); try {FileOutputStream fos = new FileOutputStream (file); // write the username and password, write the data in name # passwd format // The length of the data to be written. The unit is byte int len = (name + # + passwd ). getBytes (). length/8; if (sdcardAvailable (len) {fos. write (name ##+ passwd ). getBytes ();} else {Toast. makeText (this, sdcard insufficient storage space, Toast. LENGTH_SHORT ). show () ;}// close the output stream fos. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} Toast. makeText (this, logon successful, Toast. LENGTH_SHORT ). show ();}


 

That is, when reading and writing, first judge whether the sdcard is already running, if the status of the sdcard is OK. Then, perform the following operations.
 

 

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.