5. Use Files for data storage

Source: Internet
Author: User

Most of the time, the software we develop needs to store the processed data for re-access. Android provides the following methods for data storage:

File SharedPreferences (parameter) SQLite database Content provider (Content provider)

Network

First, we will introduceHow to store data using files

Activity provides the openFileOutput () method to output data to a file. The specific implementation process is the same as saving data to a file in the J2SE environment.

Public class FileActivity extends Activity {

@ Override
Public void onCreate (Bundle savedInstanceState ){

FileOutputStream outStream = this. openFileOutput ("ljq.txt", Context. MODE_PRIVATE );

OutStream. write ("My name is Lin ji qin". getBytes ());

OutStream. close ();

}

}

OpenFileOutput (fileName, mode)

First parameter:

It is used to specify the file name and cannot contain the path separator "/". If the file does not exist, Android automatically creates it. The created file is saved in the/data/<packagename>/files directory, for example,/data/com. ljq. activity/files/itcast.txt, click "Window"-"Show View"-"Other" in the MyEclipse menu ",

Expand the android folder in the dialog box, select the File Explorer view below, and expand the/data/<package name>/files directory in the File Explorer view to view the File.

Second Parameter

It is used to specify the operation mode. There are four modes.

Context. MODE_PRIVATE = 0

The default operation mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file.

You can use Context. MODE_APPEND.

Context. MODE_APPEND = 32768

Check whether the file exists. If yes, append the content to the file. Otherwise, create a new file.

Context. MODE_WORLD_READABLE = 1

Indicates that the current file can be read by other applications.

Context. MODE_WORLD_WRITEABLE = 2

Indicates that the current file can be written by other applications.

Note:

Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE are used to control whether other applications have the permission to read and write the file.

If you want the file to be read and written by other applications, You can input: openFileOutput ("ljq.txt", Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE );

Androidhas a set of security models. When the application program (.apk) is installed, the system will assign a userid to it. When the application wants to access other resources, such as files, it needs to match the userid. By default, files created by any application, sharedpreferences, and databases, should be private (in/data/<package name>/files), and cannot be accessed by other programs. Unless Context. MODE_WORLD_READABLE or Context. MODE_WORLD_WRITEABLE is specified during creation, only other programs can access it correctly.

To open a file that is private to the application in the/data/<package name>/files directory, you can use the openFileInput () method provided by Activity.

FileInputStream inStream = this. getContext (). openFileInput ("ljq.txt ");

Or directly use the absolute path of the file:

File file = new File ("/data/com. ljq. action/files/ljq.txt ");

FileInputStream inStream = new FileInputStream (file );

Note: The "com. ljq. action" in the above file path is the package of the application. When writing code, replace it with the package used by your own application.

A private file can only be accessed by the application that creates the file. If you want the file to be read and written by other applications, you can,

Specify the Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE permissions.

Activity also provides the getCacheDir () and getFilesDir () methods:

The getCacheDir () method is used to obtain the/data/<package name>/cache directory.

The getFilesDir () method is used to obtain the/data/<package name>/files directory.

Case

FileService: File Access Operations

Package com. ljq. service;

Import java. io. ByteArrayOutputStream;
Import java. io. InputStream;
Import java. io. OutputStream;

Public class FileService {

/**
* Save data
*
* @ Param outputStream
* @ Param content
* @ Throws Exception
*/
Public static void save (OutputStream outputStream, String content) throws Exception {
OutputStream. write (content. getBytes ());
OutputStream. close ();
}

/**
* Read data
*
* @ Param inputStream
* @ Return
* @ Throws Exception
*/
Public static String read (InputStream inputStream) throws Exception {
// Write data to memory
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ();
// Buffer zone
Byte [] buffer = new byte [1024];
Int len =-1;
While (len = inputStream. read (buffer ))! =-1 ){
ByteArrayOutputStream. write (buffer, 0, len );
}
// Store data
Byte [] data = byteArrayOutputStream. toByteArray ();
ByteArrayOutputStream. close ();
InputStream. close ();
Return new String (data );
}
}

FileServiceTest test class

Package com. ljq. service;

Import java. io. InputStream;
Import java. io. OutputStream;

Import android. content. Context;
Import android. test. AndroidTestCase;
Import android. util. Log;

/**
* Android Testing
*
* @ Author jiqinlin
*
*/
Public class FileServiceTest extends AndroidTestCase {
Private final String TAG = "FileServiceTest ";
Public void testSave () throws Exception {
OutputStream outputStream = this. getContext (). openFileOutput ("ljq.txt", Context. MODE_PRIVATE );
FileService. save (outputStream, "abc ");
}

Public void testRead () throws Exception {
InputStream inputStream = this. getContext (). openFileInput ("ljq.txt ");
String content = FileService. read (inputStream );
Log. I (TAG, content );
}
}

Configuration File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ljq.activity"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
<activity android:name=".FileActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
<uses-sdk android:minSdkVersion="7" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.ljq.activity" android:label="Tests for My App" />
</manifest>

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.