Android File data storage

Source: Internet
Author: User

First, the File preservation data Introduction

Activity provides the Openfileoutput () method that can be used to output data to a file, and the implementation process is the same as saving data to a file in a J2SE environment. Files can be used to store large amounts of data, such as text, books, audio, and so on.

The file object is suitable for reading or writing large amounts of data in the order from start to finish without skipping. For example, it is suitable for picture files or any content exchanged over the network.

The default location for data storage is:/data/data/< package name >/files/***.***.

All Android devices have two file storage areas: "Internal" and "external" storage. This article mainly stores the data so that the files are stored in the "internal" storage area.

Second, use Method 1. Writing content to a file
Try {       mcontext.openfileoutput (mfilename,context.mode_private);       Fos.write (Info.getbytes ());       Fos.close ();} Catch (Exception e) {       e.printstacktrace ();}

The first parameter of the Openfileoutput () method specifies the file name, cannot contain the path delimiter "/", and if the file does not exist, Android automatically creates it, and the second parameter of the Openfileoutput () method is used to specify the mode of operation.

Operating modes are:

Context.mode_private = 0: For the default mode of operation, the representative changes the file when the private data, can only be accessed by the application itself, in the change mode, the content will overwrite the original file content, if you want to append the new write content to the original file, you can use Context.mode_ APPEND. Context.mode_append = 32768: The mode checks whether the file exists, appends it to the file, or creates a new file. Context.mode_world_readable and context.mode_world_writeable are used to control whether other apps have permission to read and write files. context.mode_world_readable = 1: Indicates that the current file can be read by another application. Context.mode_world_writeable = 2: Indicates that the current file can be written by another application. If you want the file to be read and written by another app, you can pass in context.mode_world_readable+context.mode_world_writeable. Android has its own security model, and when the app (. apk) is installed, the system assigns it a userid, which requires a UserID match when the public is going to access other resources such as files, by default, any file created by the app, Sharedprefrences, the database should be private, and other programs cannot access it. Unless Context.mode_world_readable or context.mode_world_writeable are created at the time of creation, only such other programs can access them normally. 2. Read in the file contents
Try {            = mcontext.openfileinput (mfilename);             New BufferedReader (new  inputstreamreader (FIS));             = reader.readline ();            Fis.close ();             return info;  } Catch (Exception e) {            e.printstacktrace ();  }
Three, small case 1. Add Strings.xml file
   <stringname= "Write_data">Write Data</string>   <stringname= "Read_data">Reading data</string>   <stringname= "File">File</string>
2. Modify the Activity_main.xml file
<TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/file"android:layout_gravity= "Center_horizontal"        />    <LinearLayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:orientation= "Horizontal"Android:layout_margintop= "@dimen/fab_margin"Android:layout_marginbottom= "@dimen/fab_margin"        >        <ButtonAndroid:id= "@+id/file_write"Android:layout_height= "Wrap_content"Android:layout_width= "0DP"Android:layout_weight= "1"Android:text= "@string/write_data" />        <ButtonAndroid:id= "@+id/file_read"Android:layout_height= "Wrap_content"Android:layout_width= "0DP"Android:layout_weight= "1"Android:text= "@string/read_data" />    </LinearLayout>
3. Add Filedbmanager Class
 PackageCom.zhangmiao.datastoragedemo;ImportAndroid.content.Context;Importandroid.os.Environment;ImportAndroid.util.Log;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.InputStreamReader;ImportJava.io.ObjectOutputStream;/*** Created by Zhangmiao on 2016/12/20.*/ Public classFiledbmanager {PrivateFile Mfile; PrivateContext Mcontext; PrivateString mfilename = "MyFile";  PublicFiledbmanager (Context context) {Mcontext=context; }     Public voidWrite (String info) {Try{FileOutputStream fos=Mcontext.openfileoutput (mfilename,context.mode_private);            Fos.write (Info.getbytes ());        Fos.close (); }Catch(Exception e) {e.printstacktrace (); }    }     PublicString Read () {Try{FileInputStream fis=Mcontext.openfileinput (mfilename); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (FIS)); String Info=Reader.readline ();            Fis.close (); returninfo; }Catch(Exception e) {e.printstacktrace (); }        return""; }}
4. Modify Mainactivity
 PackageCom.zhangmiao.datastoragedemo;ImportAndroid.content.ContentResolver;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;ImportAndroid.net.Uri;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;Importjava.util.ArrayList;Importjava.util.List; Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener {PrivateFiledbmanager Mfilemanager;PrivateTextView Mtableinfo; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_main);Mfilemanager=NewFiledbmanager ( This);Mtableinfo=(TextView) Findviewbyid (r.id.table_info);Filewrite.setonclicklistener ( This); Fileread.setonclicklistener ( This);    }@Override Public voidOnClick (View v) {Switch(V.getid ()) {
CaseR.id.file_write:mfilemanager.write ("Hello world!"); Break; CaseR.id.file_read:mtableinfo.settext (Mfilemanager.read ()); Break ;default: Break; } }}

Android File data 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.