"Android data store"-File

Source: Internet
Author: User


Individual learning to organize. If you have any shortcomings, please do not hesitate to enlighten me.

Reprint Please specify: @CSU-max


read and write files in this application Data directoryThis method reads and writes files in the/data/data/< application package name >Openfileinput ( String fileName) and available in Android 1>openfileoutput (String fileName, int mode) Two methods to read and write to files in the data directory of this application.                 openfileinput (string  filename )     open File input stream Openfileoutput ( String fileName, int mode) to open the file output stream Note:the parameters inopenfileoutput (String fileName, int mode) mode specifies the form in which the file opens: mode_private: This file can only be read and written by the current program mode_append: Open File in Append mode, application can append content to file mode_world_readable: The contents of this file can be read by other applications mode_world_writeable: The contents of this file can be read and written by other applications Example: The file input section of this instance program interface has an input box and a button. Click button to write the information entered in the input box to the specified file; The Read section has a text box and a button, and clicking the button text box displays the contents of the specified file.

read: write:
Verify write:

Instance code:
Package Com.example.filedemo;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.printstream;import Android.os.bundle;import Android.app.activity;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import android.widget.textview;/** * * @author Csumax * @version 1.0 2014-4-24 */public class Mainactivity extends Activity {pri Vate Button bt_main_in; Write file buttonprivate Button bt_main_out; Read file buttonprivate EditText et_main_in;//input text box private TextView tv_main_out;//display file contents @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); bt_main_in = (Button) This.findviewbyid (R.id.bt _main_in) Bt_main_out = (Button) This.findviewbyid (r.id.bt_main_out); et_main_in = (EditText) This.findviewbyid ( r.id.et_main_in) Tv_main_out = (TextView) This.findviewbyid (r.id.tv_main_out);//click button to write the contents of the input box to the file Bt_main_ In.setonclicklistener (New ONclicklistener () {@Overridepublic void OnClick (View v) {String fileName = "Demo.txt"; String text = Et_main_in.gettext (). toString (); WriteToFile (text, fileName); Et_main_in.settext ("");}}); /Click button to read the contents of the file and display it in the text box Bt_main_out.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View V {String FileName = "Demo.txt"; Tv_main_out.settext (ReadFromFile (FileName);}});} /** * Read File * * @param fileName * @return */public string readfromfile (string filename) {try {FileInputStream FIS = openfi Leinput (FileName); byte[] bytes = new byte[1024]; StringBuffer sb = new StringBuffer (), int i = 0;i = Fis.read (bytes), if (i > 0) {sb.append (New String (bytes, 0, i));} return sb.tostring ();} catch (Exception e) {e.printstacktrace ();} return null;} /** * Write to File * * @param text * Write content * @param filename * file name of the destination file */public void WriteToFile (String t Ext, String fileName) {try {//mode_append mode write. That is, append mode fileoutputstream fos = Openfileoutput (FileName, mode_append); PrintStream PS= new PrintStream (FOS);p s.println (text);p s.close ();} catch (Exception e) {e.printstacktrace ();}}}

the Demo.txt file in the program can be seen through the/data/data/< application package name >/files/demo.txt in the file Explorer, for example, as seen (because there are many unrelated files, so separate truncation into two pictures):


read the files in the resource file
here, for example, read the resource raw file, create a new raw directory under the Res directory and copy the previous Demo.txt file.     
Main code:
public class Readfileutil {public    static string Readfromraw (context context, int id) {        string str = "";        try {            //Get input stream            InputStream is = Context.getresources (). Openrawresource (ID);            int length = is.available ();            byte[] bytes = new Byte[length];            int i = 0;            i = Is.read (bytes);            if (i > 0) {                //set encoding                str = encodingutils.getstring (bytes, "UTF-8");            }            Is.close ();            return str;        } catch (Exception e) {            //Todo:handle Exception        }        return null;}    }

Test Code:
public class Readertest extends Androidtestcase {    private static final String TAG = "Readertest";    public void Testreadfromraw () {        log.i (TAG, "---------------");        String str = "Failed";        str = Readfileutil.readfromraw (GetContext (), R.raw.demo);        LOG.I (TAG, "========>" + str + "<========");}    }

Note: The file under the resource file is visited by the ID identified in the R file, so r.raw. Demo .
read and write files on SD card
Sometimes we store some data on the SD card. Now let's simulate it. In the file Explorer view, Add the previous Demo.txt file to the/mnt/sdcard/folder. Now try to read the information in the file and write the information to it.     
Main code:
public class Readfileutil {public static string Readfromsdcard (String fileName) {string str = "";            try {fileinputstream fis = new FileInputStream (fileName);            int length = fis.available ();            byte[] bytes = new Byte[length];            int i = 0;            i = Fis.read (bytes);            if (i > 0) {//set encoding str = encodingutils.getstring (bytes, "UTF-8");            } fis.close ();        return str;    } catch (Exception e) {//Todo:handle Exception} return null;  }/** *-Note that when writing information to a file in an SD card, add the corresponding permission in the Androidmanifest.xml file--*/public static void Writetosdcard (String text, String FileName {The second parameter of the try {//constructor method indicates an append mode fileoutputstream fos = new FileOutputStream (filen            Ame, True);            byte[] bytes = Text.getbytes ();            Fos.write (bytes);        Fos.close (); } catch (Exception e) {E.priNtstacktrace (); }    }    }

Test Code:
public class Readertest extends Androidtestcase {    private static final String TAG = "Readertest";     public void Testreadfromsdcard () {        log.i (TAG, "---------------");        String str = "Failed";        str = Readfileutil.readfromsdcard ("/mnt/sdcard/demo.txt");        LOG.I (TAG, "========>" + str + "<========");    }        public void Testwritetosdcard () {        log.i (TAG, "---------------");        String Text = "Max";        Readfileutil.writetosdcard (text, "/mnt/sdcard/demo.txt");}    }

Note:generally read and write files in this application to use openfileinput and openfileoutput. Fileinputstrea and FileOutputStream are required to read and write the files in the SD card .

By default, the files in the SD card have only the readable permission, so it is necessary to add the corresponding permission when writing data to the SD card.
    <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission Android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>



                                   ,         &NB Sp       ***************************************************************************

                                  & nbsp;                 *   Reprint Please specify source:   @CSU-max     http://blog.csdn.net/csu_max      *

***************************************************************************



"Android data store"-File

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.