Getting started with Android: file storage

Source: Internet
Author: User
Document directory
  • 1.
  • Step 1: Set the simulator to support sdcard
  • Step 2: Set permissions in the Application
  • Note:
  • Suggestion:

There are multiple ways to store data, such as database storage, sharedpreferences storage, and file storage;

Here we will introduce the simplest file storage method;

In simple terms, file storage is the IO stream in the general javase, but it is only applied to Android phones;

I. Core code of file storage

File Storage


(1) fileoutputstream out = context. openfileoutput (string filename, int mode); get the file output stream in Mode

(2) Out. Write (byte [] B );

FileOutputStream out = null;out = context.openFileOutput(filename, Context.MODE_***);out.write(filecontent.getBytes("UTF-8"));out.close();

Note: files are stored in/data/package/files by default;

File Reading


(1) fileinputstream in = context. openfileinput (string filename); get the file stream of a file

(2) int length = in. Read (byte []);

/* Each time a fixed byte is read and the byte is output to the byte output stream. After all the data is read, the content in the byte stream is output together */fileinputstream in = NULL; bytearrayoutputstream bout = NULL; byte [] Buf = new byte [1024]; bout = new bytearrayoutputstream (); int length = 0; In = context. openfileinput (filename); // get the input stream while (length = in. read (BUF ))! =-1) {bout. write (BUF, 0, length);} byte [] content = bout. tobytearray (); filecontentet. settext (new string (content, "UTF-8"); // set the text box to read content in. close (); bout. close ();

Note: files of/data/package/files are read by default;

II. Introduction to file Mode

1. Context. mode_private:Private overwrite Mode
-RW ----

It can only be accessed by the current application and overwritten if it is written;

2. Context. mode_append:Private append Mode
-RW ----

It can only be accessed by the current application, and if it is written, it will be appended;

3. Context, mode_world_readable:Public read-only mode-RW-r --

Can be read by other applications;

4. Context. mode_world_writeable:Public writable mode-RW--w-

Can be written by other applications, but cannot be read;

Note: If you want others to make the file mode overlay, you can use the plus sign to connect;

For example, context. mode_world_readable+Context. mode_world_writeable indicates that other applications read and write data;

3. Simple Application Example 1.

Purpose: When you click "save", the content will be saved with a specific file name and specific file content. When you click "read", the file content read from a specific file will be displayed in the file content text box;

After you click Save, the effect is as follows:

Mainactivity. Java

Package Org. xiazdong. file; import Java. io. bytearrayoutputstream; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import android. app. activity; import android. content. context; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; public class mainactivity ex Tends activity {private button savebutton, readbutton; private edittext filenameet, filecontentet; private context = This; private onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view V) {If (V = savebutton) {string filename = filenameet. gettext (). tostring (); string filecontent = filecontentet. gettext (). tostring (); fileoutputstream out = NULL; try {out = context. openfile Output (filename, context. mode_private); out. write (filecontent. getbytes ("UTF-8");} catch (exception e) {e. printstacktrace ();} finally {try {out. close ();} catch (exception e) {e. printstacktrace () ;}} else if (V = readbutton) {string filename = filenameet. gettext (). tostring (); // The name of the file to be read. fileinputstream in = NULL; bytearrayoutputstream bout = NULL; byte [] Buf = new byte [1024]; bout = new bytearrayoutputstream (); Int length = 0; try {In = context. openfileinput (filename); // get the input stream while (length = in. Read (BUF ))! =-1) {bout. write (BUF, 0, length);} byte [] content = bout. tobytearray (); filecontentet. settext (new string (content, "UTF-8"); // set the text box to read content} catch (exception e) {e. printstacktrace ();} filecontentet. invalidate (); // refresh the screen try {In. close (); bout. close () ;}catch (exception e) {}};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); savebutton = (button) This. findviewbyid (R. id. savebutton); readbutton = (button) This. findviewbyid (R. id. readbutton); filenameet = (edittext) This. findviewbyid (R. id. filename); filecontentet = (edittext) This. findviewbyid (R. id. filecontent); savebutton. setonclicklistener (listener); readbutton. setonclicklistener (listener );}}
4. Save the file to sdcard

If a file is large, it is not applicable to storage on mobile phones;

If the mobile phone has an sdcard, the Directory of the sdcard is/Mnt/sdcardDirectory;

Step 1: Set the simulator to support sdcard

Now the simulator supports sdcard;

Step 2: Set permissions in the Application

Set in androidmanifest. xml:

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

Core code stored in sdcard:

File f = new File(Environment.getExternalStorageDirectory(),filename);out = new FileOutputStream(f,true);out.write(filecontent.getBytes("UTF-8"));

Read the core sdcard code:

File f = new File(Environment.getExternalStorageDirectory(),filename);in = new FileInputStream(f);while((length=in.read(buf))!=-1){bout.write(buf,0,length);}byte[] content = bout.toByteArray();

In fact, it is mainly about the storage directory;

Note:

In Android, The sdcard directory of 1.5 and 1.6 is/sdcard, while android2.0 and above are all/mnt/sdcard. Therefore, if we directly write a specific directory during storage, we can use:

Environment. getexternalstoragedirectory ();Obtain the sdcard directory;

Suggestion:

(1) You cannot simply use the sdcard deposit method, because if you cannot determine whether a mobile phone has an sdcard, if not, you need to provide other solutions, such

Save to mobile phone storage;

The system prompts that the sdcard does not exist;

You can use:

If (environment. getexternalstoragestate (). Equals (environment. media_mounted) {// execute the storage sdcard method} else {// store it to your phone, or prompt}

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.