Android: File storage

Source: Internet
Author: User
Tags logical operators

Data persistence means that the instantaneous data in memory is saved to the storage device, ensuring that the data is not lost even when the phone or computer shuts down. The data stored in memory is instantaneous, while the data stored in the storage device is persisted, and persistence provides a mechanism for transforming the data between the transient state and the persistent state.

Persistence technology is widely used in various programming fields, and the nature of this book is to explore the data persistence technology in Android. The Android system offers three ways to simply implement data persistence, namely file storage, Sharedpreference storage, and database storage. Of course, in addition to these three ways, you can also save the data in the phone's SD card, but the use of files, sharedpreference or database to save the data is relatively simpler, and more than the data saved in the SD card will be more secure.

File storage is the most basic form of data storage in Android, it does not do any formatting of the stored content, all the data is stored intact in the file, so it is more suitable for storing some simple text data or binary data. If you want to use file storage to save some more complex text data, you need to define a set of your own formatting specifications, which makes it easier to re-parse the data from the file later.

So first, let's take a look at how Android uses files to save data.

6.2.1 storing data in a file

A Openfileoutput () method is provided in the Context class that can be used to store data in the specified file. This method receives two parameters, the first parameter is the file name, the name is used in the creation of the document, note that the file name specified here can not contain the path, because all the files are stored by default to the/data/data/<package name>/files/directory Under the. The second parameter is the mode of operation of the file, there are two main modes to choose from, Mode_private and Mode_append. Where mode_private is the default mode of operation, indicating that when the same file name is specified, the content written will overwrite the contents of the original file, and mode_append means that if the file already exists, it will append content to the file and create a new file if it does not exist. In fact, there are two other modes of operation of the file, Mode_world_readable and Mode_world_writeable, both of which allow other applications to read and write to the files in our program, but because these two modes are too dangerous, Vulnerability to application vulnerabilities is now deprecated in Android version 4.2.

The Openfileoutput () method returns a FileOutputStream object that can be used to write data to a file using the Java stream. Here's a simple code example that shows how to save a piece of text to a file:

Public Void Save () {

String data = "Data to save"; FileOutputStream out = null; BufferedWriter writer = null; try {

out = Openfileoutput ("Data", context.mode_private);

writer = new BufferedWriter (new OutputStreamWriter (out));

Writer.write (data);

} catch (IOException e) {

E.printstacktrace ();

} finally {

try {

if (writer! = null) {

Writer.close ();

}

} catch (IOException e) {

E.printstacktrace ();

}

}

}

If you're already familiar with Java streaming, it's easy to understand the code above. Here, the Openfileoutput () method is used to get a FileOutputStream object, then build a OutputStreamWriter object with it, and then use the OUTPUTST Reamwriter constructs a BufferedWriter object so that you can write the text content to the file by BufferedWriter.

Let's write a complete example to learn how to use file storage in Android projects. First create a Filepersistencetest project and modify the code in the Activity_main.xml as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" >

<edittextandroid:id= "@+id/edit" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:hint= "Typesomething Here"

/>

</LinearLayout>

This simply adds a EditText to the layout to enter the text content. In fact, now you can run the program, the interface will definitely have a text input box. Then in the text input box random input what content, and then press the back key, then the input content must have been lost, because it is only instantaneous data, after the activity has been destroyed will be recycled. And what we're going to do here is store it in a file before the data is recycled. Modify the code in the mainactivity as follows:

public class Mainactivity extends Activity {

Private EditText edit;

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

Edit = (EditText) Findviewbyid (R.id.edit);

}

@Override

protected void OnDestroy () {

Super.ondestroy ();

String Inputtext = Edit.gettext (). toString ();

Save (Inputtext);

}

public void Save (Stringinputtext) {fileoutputstream out = null; BufferedWriter writer = null;

try {

out = Openfileoutput ("Data", context.mode_private);

writer = new BufferedWriter (new OutputStreamWriter (out));

Writer.write (Inputtext);

} catch (IOException e) {

E.printstacktrace ();

} finally {

try {

if (writer! = null) {

Writer.close ();

}

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

As you can see, first we get an instance of EditText in the OnCreate () method, and then rewrite the OnDestroy () method, which guarantees that this method will be called before the activity is destroyed. In the OnDestroy () method we get the input in the EditText and call the Save () method to store the input into a file named data. The code in the Save () method is basically the same as the previous example, and is no longer explained here. Now rerun the program and enter some content in Editext, as shown in 6.1.

Figure 6.1

Then press the back key to close the program, and the content we entered is saved to the file. So how can you confirm that the data has been successfully saved? We can take a look at it with the DDMS File Explorer. Switch to the DDMS view and click on the File Explorer switch card, where you go to/data/data/com.example. In the filepersistencetest/files/directory, you can see that a data file was generated, as shown in 6.2.

Figure 6.2

Then click on the leftmost button in Figure 6.3 to export the file to your computer.

Figure 6.3

Use Notepad to open this file, as shown in content 6.4.

Figure 6.4

This confirms that the content entered in the EditText has been successfully saved to the file. But it's not enough to save the data successfully, and we need to find a way to make it the next time you start the program.

The data can be restored to EditText, so next we'll learn how to read the data from the file.

6.2.2 reading data from a file

Similar to storing data in a file, the Context class also provides a Openfileinput () method for reading data from a file. This method is simpler than openfileoutput (), it takes only one parameter, that is, the name of the file to be read, and then the system automatically loads the file into the/data/data/<package name>/files/directory. and returns a FileInputStream object that can be read by the Java stream after the object is obtained.

Here's a simple code example that shows how to read text data from a file:

Public String Load () {fileinputstream in = null; BufferedReader reader = null;

StringBuilder content = new StringBuilder ();

try {

in = Openfileinput ("Data");

reader = new BufferedReader (Newinputstreamreader (in)); String line = "";

while (line = Reader.readline ()) = null) {

Content.append (line);

}

} catch (IOException e) {

E.printstacktrace ();

} finally {

if (reader! = null) {

try {

Reader.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

return content.tostring ();

}

In this code, a FileInputStream object is first obtained through the Openfileinput () method, then a InputStreamReader object is built with it, and then the InputStreamReader Build a BufferedReader object so that we can read through the BufferedReader line, read all the text in the file, and store it in a StringBuilder object, and finally return the read content.

Knowing how to read data from a file, we will continue to refine the example in the previous section so that we can keep our last input when restarting the program EditText. Modify the code in the mainactivity as follows:

public class Mainactivity extends Activity {

Private EditText edit;

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

Edit = (EditText) Findviewbyid (R.id.edit);

String inputtext = load ();

if (! Textutils.isempty (Inputtext)) {edit.settext (inputtext); Edit.setselection (Inputtext.length ()); Toast.maketext (This, "restoringsucceeded",

Toast.length_short). Show ();

}

}

......

Public String Load () {fileinputstream in = null; BufferedReader reader = null;

StringBuilder content = new StringBuilder ();

try {

in = Openfileinput ("Data");

reader = new BufferedReader (Newinputstreamreader (in)); String line = "";

while (line = Reader.readline ()) = null) {

Content.append (line);

}

} catch (IOException e) {

E.printstacktrace ();

} finally {

if (reader! = null) {

try {

Reader.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

return content.tostring ();

}

}

As you can see, the idea here is very simple, call the load () method in the OnCreate () method to read the contents of the text stored in the file, and if the read is not empty, call EditText's SetText () method to populate the EditText with the content, and call The SetSelection method moves the input cursor to the end of the text to make it easier to enter, and then pops up a prompt to restore the success. The details in the load () method have already been mentioned, and we will not repeat them here.

Note that the above code uses the Textutils.isempty () method when making a non-null judgment on a string, which is a very useful method that can be used to judge two null values at once. This method returns True when the passed-in string equals null or is equal to an empty string, so that we do not need to judge the two null values individually, and then use the logical operators to join them.

Now rerun the program, the content string you just saved will definitely be populated into EditText, and then write something else, such as enter Hello in EditText, then press the back key to exit the program, and then restart

The input is not lost, but is restored to the EditText, as shown in 6.5.

Figure 6.5

In this way we have learned the knowledge of file storage, in fact, the core technology used is the Openfileinput () and the Openfileoutput () method provided in the context class, then the use of various Java streams to read and write operations can be.

But as I said earlier, the way the file is stored is not suitable for storing some of the more complex text data, so let's learn another way to persist the data in Android, which is easier to use than file storage, and it's easy to read and write to a given data.

Android: File storage

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.