Android learning 10 (android file storage) and android file storage

Source: Internet
Author: User

Android learning 10 (android file storage) and android file storage

The android system provides three methods for simple data persistence, namely file storage, SharePreference storage, and database storage. You can also save the data to the SD card.

File storage is the most basic data storage method in android. It does not process the stored content in any format. All data is stored in the file intact, therefore, it is suitable for storing some simple text or binary data.

The Context class provides an openFileOutput () method to store data in a specified file. This method receives two parameters. The first parameter is the file name, which is used when the file is created. Note that the specified file name does not contain the path, because all files are stored in the/data/<package>/files/directory by default. The second parameter is the file operation mode. There are two modes available: MODE_PRIVATE and MODE_APPEND. MODE_PRIVATE is the default operation mode, indicating that when the same file name is specified, the written content will overwrite the content in the original file, MODE_APPEND indicates that if the file already exists, content will be appended to the file. If the file does not exist, a new file will be created.

The openFileOutput () method returns a FileOutputStream object. After obtaining this object, you can use java stream to write data to the file.



Save data to a file


Create an android project named FilePersistenceTest and modify the code in activity_main.xml. The Code is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"     >   <EditText        android:id="@+id/edit"       android:layout_width="match_parent"       android:layout_height="wrap_content"       android:hint="type something here"       /></LinearLayout>


What we need to do below is to save the data and save the data to the file when the activity is destroyed. Modify the code in MainActivity:

Package com. jack. filepersistencetest; import java. io. bufferedWriter; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. outputStreamWriter; import android. OS. bundle; import android. app. activity; import android. content. context; import android. view. menu; import android. widget. editText; public class MainActivity extends Activity {private EditText editText; @ Overrideprotected vo Id onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); editText = (EditText) findViewById (R. id. edit) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} public void save (String inputText) {FileOutputStream f IleOutputStream = null; // file output stream object BufferedWriter bufferedWriter = null; // Character Buffer Stream object try {// initialize file output stream object fileOutputStream = openFileOutput ("datafile", Context. MODE_PRIVATE); // initialize the character buffer Stream object bufferedWriter = new BufferedWriter (new OutputStreamWriter (fileOutputStream); // write the string bufferedWriter to the buffer memory. write (inputText);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {try {if (bufferedWriter! = Null) {bufferedWriter. close (); // close the file} catch (Exception e) {e. printStackTrace () ;}}@ Overrideprotected void onDestroy () {// TODO Auto-generated method stubsuper. onDestroy (); String inputText = editText. getText (). toString (); // get the content in the text box save (inputText); // save the information in the text box }}


When the onDestroy method is called during activity destruction, the save method is called to save the content in the text box. Run the program and enter hello world in the text box, for example:



Press the back key to close the program. The entered content is saved to the file. We can open the file explorer of ddms to view it. In file explorer, enter the/data/com. jack. filepersistencetest/files/directory. You can see that the datafile file is generated, for example:




Click the leftmost button on the right to export the file to the computer, and then open the file in a text editor. The content in the file is as follows:

It can be confirmed that the content in the text box has been saved to the file.



Read data from a file

Similar to storing data in files, the Context class also provides an openFileInput Method for reading data from files. This method is relatively simple. Only one parameter is received, that is, the file name to be read. Then the system automatically loads the file under the/data/<package>/files/directory, return a FileInputStream object. After obtaining this object, you can read the data through java stream.

Modify the code in MainActivity as follows:

Package com. jack. filepersistencetest; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import android. OS. bundle; import android. app. activity; import android. content. context; import android. text. textUt Ils; import android. view. menu; import android. widget. editText; import android. widget. toast; public class MainActivity extends Activity {private EditText editText; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); editText = (EditText) findViewById (R. id. edit); String inputText = load (); if (! TextUtils. isEmpty (inputText) {editText. setText (inputText); editText. setSelection (inputText. length (); Toast. makeText (this, "Restoring succeeded", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} public void save (String inputText) {FileOutp UtStream fileOutputStream = null; // file output stream object BufferedWriter bufferedWriter = null; // Character Buffer Stream object try {// initialize file output stream object fileOutputStream = openFileOutput ("datafile ", context. MODE_PRIVATE); // initialize the character buffer Stream object bufferedWriter = new BufferedWriter (new OutputStreamWriter (fileOutputStream); // write the string bufferedWriter to the buffer memory. write (inputText);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {try {if (buffere DWriter! = Null) {bufferedWriter. close (); // close the file} catch (Exception e) {e. printStackTrace () ;}}@ Overrideprotected void onDestroy () {// TODO Auto-generated method stubsuper. onDestroy (); String inputText = editText. getText (). toString (); // get the content in the text box save (inputText); // save the information in the text box} public String load () {FileInputStream in = null; // file input stream BufferedReader reader = null; // Character Buffer stream StringBuffer content = new StringBuffer (); // StringBuffer object tr Y {in = openFileInput ("datafile"); // obtain the file input stream reader = new BufferedReader (new InputStreamReader (in); // obtain the buffer object String line = ""; // while (line = reader. readLine ())! = Null) {// read a row of content. append (line); // Add the read content to content} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (reader! = Null) {try {reader. close (); // close the read stream} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} return content. toString (); // return string }}

The setSelection method moves the input cursor to the end of the text so that the input can be continued. A message indicating successful restoration is displayed.

TextUtils. the isEmpty () method can be used to judge two types of values at a time. When the input string is equal to null or null, this method returns true, so that we do not need to judge the two null values separately.

Run the program again. The effect is as follows:




File storage is not suitable for storing complex data and more complex data storage methods. I will summarize them later.



Reprint please note to: http://blog.csdn.net/j903829182/article/details/40924441



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.