Android Learning Note (43): File access

Source: Internet
Author: User
Tags throwable

Previously we learned to store data through the preference and SQLite databases, as well as through file mode. The file can be provisioned when the app is packaged, or it can be generated by the app.

There are two ways to access files: static data files can be prevented in the Res/raw, these files are read-only, only when the application version of the upgrade to make changes, or we first read the data, through the reference way to deal with, so that later can be revised, but this way, There will be two copies of the data saved. Second: Another way is to access the file through a URL, Dynamic Data reading can also be used SQLite3 way.

Reading of static files under res/raw/

Store the Words.xml file under Res/raw. The XML file can actually be used to learn notes from Android (38): The resource resource (above) is placed in Res/xml. This example only shows how the file is read in Res/raw.

<words>
<word value= "lorem"/>
<word value= "ipsum"/>
<word value= "dolor"/>
<word value= "sit"/>
<word value= "amet"/>
... ...
</words>

The source code is as follows:

public class Chapter23test1 extends listactivity{
Private arraylist<string> items = new arraylist<string> ();

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
try{
Gets the file's InputStream, first obtains the resource object through Getresrouces (), and then obtains the specified file's InputStream through Openrawresource ()
InputStreamin =getresources (). Openrawresource (r.raw.words);
Interpret the XML file: Get the data from it and put it in ArrayList. Set up XML parsing, put InputStream into Dom file, and get the required data through tree structure nodelist.
Documentbuilder builder = documentbuilderfactory.newinstance (). Newdocumentbuilder ();
Document doc = Builder.parse (in,null);
NodeList
Words = Doc.getElementsByTagName("word");

for (int i = 0; i < words.getlength (); i + +) {
Elementnode = (Element) words.item (i);
Items.Add (Node.getattribute ("value"););
}
}catch (Throwable t) {
Toast.maketext (This, "Exception:" + t.tostring (), Toast.length_long). Show ();
}
Setlistadapter (New arrayadapter<string> (this,android. R.layout.simple_list_item_1,items));
}
}

Apply Private file Read

For files, more important is to support read and write operations, Android provides file read and write methods in the application directory. Here is an example of an editor with a filename called Notes.txt, located under the application Files directory:/data/data/com.wei.android.learning/files/directory. This directory is the default private folder for the application. When the editor is closed, the contents of the text box are saved to the file when it is in the background, and when it is in effect, the contents are read from the file and restored to the editor. That is, the write operation at OnPause (), Onresume () read operation. The first time you open the app, it returns an error because the file is not found, so we can track the absolute path where the file is located. Here is the source code:

public class Chapter23test2 extends activity{
Private EditText editor = null;
private static String notes= "Notes.txt";

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.CHAPTER_23_TEST2);
Editor = (EditText) Findviewbyid (r.id.c23_editor);
Button button = (button) Findviewbyid (r.id.c23_close);
Button.setonclicklistener (New View.onclicklistener () {
public void OnClick (View v) {
Click Button, execute Finish (), that is, close activty, will trigger OnPause (), in this case will trigger the write operation
Finish ();
}
});
}

Onresume () When the activity is active,Read the fileAction to place the contents of the file in the EditText component
protected void Onresume () {
Super.onresume ();

try{
/* Openfileinput (String name) is a function of the Android.content.ContextWrapper class, can be called directly in the activity, the parameter name, cannot contain the directory separator, that is, can only handle the application of private folder files, after obtaining InputStream, according to regular Java processing. If you need to access more places, you need to create a content privider to learn later */
InputStream in =Openfileinput(NOTES);
if (in = null) {
BufferedReader reader = new BufferedReader (new InputStreamReader (in));
String str;
StringBuffer buf = new StringBuffer ();
while ((str = reader.readline ()) = null) {
Buf.append (str + "\ n");
}
In.close ();
Editor.settext (Buf.tostring ());
}
}catch (Throwable t) {
Toast.maketext (This, "Exception:" + t.tostring (),). Show ();
}
}

OnPause () When the activity is invalid,Write a fileOperation
protected void OnPause () {
Super.onpause ();
try{
/* Openfileoutput (String name, int mode) mode is on, 0 or mode_private is the default mode, mode_append means adding after the file, Mode_world_ Readable and mode_world_writeable are control permissions */
OutputStreamWriter out = new OutputStreamWriter (Openfileoutput(NOTES, 0));
Out.write (Editor.gettext (). toString ());
Out.close ();
}catch (Throwable t) {
Toast.maketext (This, "Exception:" + t.tostring (),). Show ();
}
}
}

In the first run activity, because there is no file, read an exception, such as the first diagram, from the toast can see the cause of the exception, there is no file, showing the path of the file store. We then fill in the input box with the contents, such as the second figure.

Press the Close button, execute Finish (), trigger the write file operation in OnPause (), and end the activity. For mobile phones, if we are in the Edit writing box, there is a call that can also trigger the OnPause () operation to save the current input. When recovering, read and recover through Onresume ().

We can view the files via the console of the ADB connection simulator as follows:

$./ADB Shell
# Cd/data/data/com.wei.android.learning/files
# ls
Notes.txt
# Cat Notes.txt
Hello, My friend! #

External storage files

You can read and write to external storage (such as an SD card). To have permissions on external storage, such as Write_external_storage. The same way that you add network permissions, set in Androidmanifest.xml:

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

Use file F = environment.getexternalstoragedirectory () to get the SD card root object. This can then be handled as a Java file operation. Detailed access to Android SDcard operations (file read/write, capacity calculation).

RELATED links: My Andriod development related articles

Android Learning Note (43): File access

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.