Android learning notes (11) ---- file read/write operations in the android private folder

Source: Internet
Author: User

/*************************************** **************************************** *************
* Author: conowen @ Dazhong
* E-mail: conowen@hotmail.com
* Http://blog.csdn.net/conowen
* Note: This article is original and only used for learning and communication. For more information, indicate the author and its source.

**************************************** **************************************** ************/

Android Data Storage

There are several ways to store file data in Android, such as shared preferences, network, SQLite, file ......

File storage can be divided into private folders and sdcard directories of applications by storage location.

Today, let's talk about the read and write operations of the Android app on private folders.

Private file storage

The private folder of an application is located under the/data/"application package name"/Files folder. Open the ddms of eclipse and you can find the file by viewing file explorer.

After creation, the user has read and write permissions. By default, the file cannot be accessed by other applications, but the permissions can be changed. After the application is installed, you can clear the data of the application in the "Settings" option of Android. You can use openfileoutput (string filename, mode) and openfileinput (string filename) to obtain a file stream (fileoutputstream) or (fileiutputstream ), call the write or read method of the file stream to implement the "write" and "read" functions.


Write operation

Openfileoutput (string filename, mode) ---- open the specified private file (string filename) in the private directory of the application to write data,

Returns a fileoutputstream object. If the object does not exist, it is created.

Official description

Parameters
Name The name of the file to open; can not contain path separators.
Mode Operating mode. Use 0 orMODE_PRIVATEFor the default operation,MODE_APPENDTo
Append to an existing file,MODE_WORLD_READABLEAndMODE_WORLD_WRITEABLE
To control permissions.
Returns
  • Fileoutputstream resulting output stream.

Constant meaning
MODE_PRIVATEDefault mode. The value is 0. files can only be accessed by applications that call this method.

MODE_APPENDIf the file already exists, write data to the end of the file instead of overwriting the original data. (Common)

MODE_WORLD_READABLEAll applications have the permission to read the file.

MODE_WORLD_WRITEABLEAll applications have the write permission on the file.

Simple file Writing Process

After the openfileoutput (string filename, mode) method is called, a fileoutputstream object is returned.

Then, you can write the file by calling the write method of the fileoutputstream object.

Fileoutputstream. Write (byte [] buffer) Although note that the write () method writes data of the byte [] type

byte[] buffer = args.getBytes();

Converts ARGs of the string type to the byte [] type. And then write.

Other operations:

Read files

Openfileinput (string filename) opens the specified private file in the private directory of the application to read data, and returns a fileinputstream object

List objects

Filelist () searches for private files in the private folder of the application, and returns a string array of all file names.

Delete an object

Deletefile (string filename) deletes the file with the specified file name. If the file is successfully deleted, true is returned. If the file fails, false is returned.

For more information, see the Demo code.

/* Author: conowen * Date: 2012.2.27 */package COM. conowen. privatefile; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Org. apache. HTTP. util. encodingutils; import android. app. activity; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. toa St; public class privatefileactivity extends activity {/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button writebt = (button) findviewbyid (R. id. write); button readbt = (button) findviewbyid (R. id. read); button delbt = (button) findviewbyid (R. id. del); writebt. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubedittext ET = (edittext) findviewbyid (R. id. et); string Etres = et. gettext (). tostring (); filewrite ("test. data ", Etres); string [] filelist = filelist (); // find the file in the private folder and return the file name toast. maketext (privatefileactivity. this, "the file name is" + filelist [0], toast. length_short ). show () ;}}); readbt. setonclicklistener (New onclicklistener (){ @ Overridepublic void onclick (view v) {// todo auto-generated method stubstring result = ""; Result = fileread ("test. data "); toast. maketext (privatefileactivity. this, result, toast. length_short ). show () ;}}); delbt. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubdelfile ("test. data ") ;}}) ;}// read Public String fileread (string filename) {// open a specified file And returns the string object string res = ""; // initialize restry {fileinputstream fileread = openfileinput (filename); // gets the object length int lenght = fileread. available (); byte [] buffer = new byte [lenght]; fileread. read (buffer); // convert the byte array to the string res = encodingutils in the specified encoding format. getstring (buffer, "UTF-8"); // file encoding} catch (exception e) {e. printstacktrace ();} return res;} // Delete public Boolean delfile (string filename) {try {Boolean del = deletefil E (filename); Return del;} catch (exception e) {e. printstacktrace ();} return false;} public void filewrite (string filename, string ARGs) {// write try {byte [] buffer = args. getbytes (); // convert the string to be written to the byte array. ARGs is the string passed in by the method: fileoutputstream out = openfileoutput (filename, mode_append); // obtain fileoutputstreamout. write (buffer); // write the byte array to the file log. I ("I", "write"); out. close (); // close the file output stream} catch (exception e) {system. err. Println ("error writing to file! ");}}}

Main. XML Code

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "@ string/Hello"/> <edittext Android: Id = "@ + ID/ET" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <button Android: Id = "@ + ID/write" Android: layout_width = "80dip" Android: layout_height = "wrap_content" Android: text = "write"/> <button Android: Id = "@ + ID/read" Android: layout_width = "80dip" Android: layout_height = "wrap_content" Android: text = "read"/> <button Android: Id = "@ + ID/del" Android: layout_width = "80dip" Android: layout_height = "wrap_content" Android: text = "delete"/> </linearlayout>

Related Article

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.