Android storage Learn to read and write files in external storage

Source: Internet
Author: User

The previous section learned how to read and write files in the phone's internal storage, and this section learns how to read and write files in the phone's external storage. That's how to read and write files in SDcard.

We also use the previous login interface example to illustrate, (login interface please see the android storage learning in the internal storage to read and write files)

First we show the written code:

When you click OK and the automatic login hook is selected, a Info.txt file is created in the SDcard folder

public void Login (View v)    {    String name = Ed_nam.gettext (). toString ();        String passwd = Ed_passwd.gettext (). toString ();        Determine if the user name or password is entered if    ((Name.equals (")) | | (Passwd.equals ("")))    {    Toast.maketext (this, "User name or password cannot be empty", Toast.length_short). Show ();    else     {    //If automatic login is checked, we will need to save the user name and password    if (cb.ischecked ())    {    //Create a file, the user saves the user name and password    file file = new File ("Sdcard/info.txt");    try {    FileOutputStream fos = new FileOutputStream (file);//write user name and password to name# #passwd的格式写入fos. Write ((name + "# #" + passwd). GetBytes ());//Close output stream fos.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}    }        Toast.maketext (This, "Login successful", Toast.length_short). Show ();}}    

After execution, the following results are displayed:


The same way you read 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);//Transfer bytes to a character stream BufferedReader buffer = new BufferedReader (new InputStreamReader (Fin));// Read the user name and password in the file string text = Buffer.readline (),//With # #为关键字分割字符String s[] = Text.split ("# #");//Set into Edittexted_nam.settext (s [0]); Ed_passwd.settext (S[1]);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Of course, the same is true. Those of us who write sdcard the path is wrong, the program is not very robust, then Google provides access to the SDcard api:getexternalstoragedirectory

    Create a file where the user saves the user name and password    //file file = new file ("Sdcard/info.txt");    File File = new file (Environment.getexternalstoragedirectory (), "info.txt");
Imagine a situation, when we write a file to SDcard, but because the sdcard capacity is limited, insufficient and put down this file, so when the user intends to put a file into the sdcard, it is necessary to determine the storage space is not satisfied, do not meet the user to give a reminder.

How to get the current available capacity of SDcard:

The user determines whether the file size exceeds SDcard's capacity public Boolean sdcardavailable (int size) {File File = Environment.getexternalstoragedirectory ( ); StatFs stat = new StatFs (File.getpath ());//the size of each block long blockSize = Stat.getblocksize ();//public divided into how many blocks long totalblocks = Stat.getblockcount ();//Total amount of space available, in bytes long availableblocks = Stat.getavailableblocks (); if (Availableblocks > Size ) {return true;} return false;}


When writing to a file, compare the available space with SDcard first:

try {    FileOutputStream fos = new FileOutputStream (file);//write the user name and password to name# #passwd的格式写入//The length of the data to be written in bytes 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 output stream fos.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}

This will prevent the file from being too large and write to half of the situation where there is insufficient capacity.


Imagine a situation where, when we suddenly write to SDcard, if there are some problems with sdcard, there is no mount, and that is not something to write. So, before you read and write, you need to determine if SDcard is working

if (cb.ischecked ())    {    //Creates a file, the user saves the user name and password    //file file = new file ("Sdcard/info.txt");        /* MEDIA_CHECKING:SD card is being prepared     * MEDIA_MOUNTED:SD card is already mounted and reading and writing access      * media_removed: No SD card     * Media_ UNKNOWN: Unrecognized SD card     * MEDIA_UNMOUNTED: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 user name and password to name# #passwd的格式写入//The length of the data to be written in bytes 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 output stream fos.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();    }}} Toast.maketext (This, "Login successful", Toast.length_short). Show ();


That is, when reading and writing, first determine whether SDcard is already running, if the state of SDcard is OK. You can then perform the next action

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android storage Learn to read and write files in external storage

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.