Android Study Notes (part 4): File Access

Source: Internet
Author: User

Previously, we learned how to store data through preference and SQLite databases, or through files. Files can be pre-packaged or generated by applications.

There are two ways to access files: 1. Files with static data can be prevented from being read-only in RES/raw and can only be modified when the application version is upgraded, or we can read the data first and use the reference method to process the data, so that the data can be modified later. However, two copies of the data will be saved in this method. 2. Another method is to access a file through a URL. You can also use sqlite3 to read dynamic data.

Read static files under Res/raw/

Store the words. xml file in RES/raw. In fact, XML files can be stored in RES/XML through the android learning notes (38): Resource (top. This example only describes how to read files stored 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 {
// Obtain the InputStream of the file. First, get the resource object through getResrouces (), and then obtain the InputStream of the specified file through openRawResource ().

InputStreamIn =GetResources (). openRawResource (R. Raw. Words);

// Interpret the XML file: Get the data from it and put it in the ArrayList. Create XML parsing, put InputStream into the DOM file, and obtain the required data through the 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 ));

}
}

Application private File Reading

For files, it is more important to support read/write operations. Android provides file read/write methods in the application directory. The file name is notes.txt, which is located in the application file directory:/data/com. wei. android. learning/files. This directory is the default private folder of the application. The editor closes the application. As for the background, the content of the text box is saved to the file. When it is valid, the content is read from the file and restored to the editor. That is, write operations are performed in onPause () and read operations are performed in onResume. When the application is opened for the first time, an error is returned because no file is found. Therefore, we can track the absolute path of the file. The source code is as follows:

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 the button and execute finish (). When activty is disabled, onPause () is triggered. In this example, the write operation is triggered.

Finish ();
}
});
}

// When onResume () is effective for the ActivityRead filesOperation: place the file content in the EditText component.

Protected void onResume (){
Super. onResume ();

Try {
/* OpenFileInput (String name) is android. content. the ContextWrapper class function can be called directly in the activity. The parameter name cannot contain directory delimiters, that is, it can only process private folder files of the application. After InputStream is obtained, it is processed in regular java. If you need to access more places, you need to create content privider and 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 (), 5000). show ();

}
}

// OnPause () indicates that the Activity is invalid.Write filesOperation

Protected void onPause (){
Super. onPause ();
Try {
/* In openFileOutput (String name, int mode), mode is the open mode, 0 or MODE_PRIVATE is the default mode, MODE_APPEND indicates adding after the file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE indicates controlling permissions */

OutputStreamWriter out = new OutputStreamWriter (Openfileoutput(Notes, 0 ));

Out. write (editor. getText (). toString ());
Out. close ();
} Catch (Throwable t ){
Toast. makeText (this, "Exception:" + t. toString (), 5000). show ();

}
}
}

When you first run the activity, an exception occurs during reading because there is no file. For example, in the first figure, the cause of the exception is displayed in Toast. The file storage path is not displayed. Then we enter the content in the input box, such as the second figure.

After pressing the Close button, execute finish () to trigger the Write File Operation in onPause () and end the Activity. If you have an incoming call in the edit box, you can also trigger the onPause () operation to save the current input. During restoration, read and restore through onResume.

We can use adb to connect to the simulator console to view the file, as shown below:

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

External storage file

You can read and write external storage (for example, SD card ). You must have permissions for external storage, such as WRITE_EXTERNAL_STORAGE. Add network permissions in the same way as in Androidmanifest. xml:

<Uses-Permission Android: Name = "android. Permission. write_external_storage"> </uses-Permission>

Use File f =Environment. getexternalstoragedirectory ()To obtain the root directory object of the SD card. Then, you can perform operations on the Java file. For details, see Android SDCard operations (file read/write and capacity calculation ).

Related Links: My Andriod development articles

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.