Read and write Android files

Source: Internet
Author: User
Tags readfile

The Android file read and write is the same as the Javase file read and write, all using IO stream. And Android is using the Javase IO stream, below we learn to read and write Android files through an exercise.

1. Create an Android project

Project Name:file

buildtarget:android2.2

Application Name: file read/write

Package Name:com.jbridge.file

Create activity:dateactivity

Min SDK Version:8

Strings.xml File Contents:

<?xml version= "1.0" encoding= "Utf-8"?>

<resources>

<string name= "App_name" > Data save </string>

<string name= "file_name" > File name </string>

<string name= "file_content" > File contents </string>

<string name= "Button_file_save" > Save </string>

<string name= "Button_file_read" > Read </string>

<string name= "file_save_success" > Save file Success </string>

<string name= "file_save_failed" > Save file failed </string>

<string name= "file_read_failed" > failed to read file </string>

</resources>

Main.xml file contents: <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "/http Schemas.android.com/apk/res/android "       android:orientation=" vertical "android:layout_width = "Fill_parent"        android:layout_height= "fill_parent" >       <!-- FileName-->       <textview android:layout_width= "fill_parent"          & nbsp    android:layout_height= "wrap_content" android:text= "@string/file_name"/>       <edittext android:layout_width= "Fill_parent"               android:layout_ height= "Wrap_content" android:id= "@+id/et_file_name"/>       <!--file contents-->   & nbsp   <textview android:layout_width= "fill_parent"               android: layout_height= "Wrap_content" android:text= "@string/file_content"/> &nbSp     <edittext android:layout_width= "fill_parent"                android:layout_height= "Wrap_content" android:minlines= "3"                Android:id= "@+id/et_file_content"/>       <!--save and read buttons with relative layout-->       <relativelayout android:layout_width= "fill_parent"                android:layout_height= "Wrap_content" >              <!--save button--               <button android:layout_width= "Wrap_content"                      android:layout_height= "wrap_content" android:text= "@ String/button_file_save "                     android:id=" @+id/bt_ Save "/>              <!--Read button-->              <button android:layout_width= "Wrap_content"    & nbsp                 android:layout_height= "wrap_content" android:layout_torightof= " @id/bt_save "                     android:text=" @string/button_ File_read "android:id=" @+id/bt_read                       and roid:layout_aligntop= "@id/bt_save"                     />        </RelativeLayout></LinearLayout>  adding Java code

Android recommends an MVC development model, so it's best to use MVC design patterns in Android app development. The MVC design pattern allows three layers to be separated, which is a good decoupling.

First we add a Fileservice.java to the project:

Package com.jbridge.service;

Import Java.io.ByteArrayOutputStream;

Import Java.io.File;

Import Java.io.FileInputStream;

Import Java.io.FileOutputStream;

Import Android.content.Context;

Import android.os.Environment;

public class Fileservice {

The parent class of the activity's parent is context,context, which is the same as the context in the other frameworks, providing us with some core manipulation tools.

Private context context;

Public Fileservice (Context context) {

This.context = context;

}

public void Savetosdcard (string filename, string content) throws exception{

if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {

File File = new file (environment.getexternalstoragedirectory (), filename);

FileOutputStream OutStream = new FileOutputStream (file);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

}

public void Save (string filename, string content) throws exception{

FileOutputStream OutStream = context.openfileoutput (filename, context.mode_private);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

Then add Filebuttononclickevent.java to the project:

Package com.jbridge.event;

Import COM.JBRIDGE.FILE.R;

Import Com.jbridge.service.FileService;

Import android.app.Activity;

Import Android.util.Log;

Import Android.view.View;

Import Android.view.View.OnClickListener;

Import Android.widget.Button;

Import Android.widget.EditText;

Import Android.widget.Toast;

public class Filebuttononclickevent implements Onclicklistener {

Get other controls by activity

private activity activity;

Read and write files through Fileservice

Private Fileservice Fileservice;

Labels for printing information

private static final String TAG = "Filebuttononclickevent";

Public filebuttononclickevent (activity activity) {

This.activity = activity;

This.fileservice = new Fileservice (activity);

}

public void OnClick (View v) {

Button button = (button) v;

Switch (Button.getid ()) {

Case R.id.bt_save:

Get file name

EditText etfilenames = (EditText) this.activity

. Findviewbyid (R.id.et_file_name);

String FileNameS = Etfilenames.gettext (). toString ();

Get file Contents

EditText etfilecons = (EditText) this.activity

. Findviewbyid (R.id.et_file_content);

String filecontents = Etfilecons.gettext (). toString ();

Save

try {

This.fileService.save (FileNameS, filecontents);

Display a special Effects message box in the window

Toast.maketext (this.activity, R.string.file_save_success,

Toast.length_long). Show ();

LOG.I (TAG, "Save file success!");

} catch (Exception e) {

Toast.maketext (this.activity, r.string.file_save_failed,

Toast.length_long). Show ();

LOG.E (TAG, e.tostring ());

}

Break

Case R.id.bt_read:

Get file name

EditText Etfilenamer = (EditText) this.activity

. Findviewbyid (R.id.et_file_name);

String Filenamer = Etfilenamer.gettext (). toString ();

Read file

try {

String fielcontentr = This.fileService.readFile (Filenamer);

EditText Etfileconr = (EditText) this.activity

. Findviewbyid (R.id.et_file_content);

Etfileconr.settext (FIELCONTENTR);

LOG.I (TAG, "read file success!");

} catch (Exception e) {

Toast.maketext (this.activity, r.string.file_read_failed,

Toast.length_long). Show ();

LOG.E (TAG, e.tostring ());

}

Break

Default

Break

}

}

}

public void Saveappend (string filename, string content) throws exception{//ctrl+shift+y/x

FileOutputStream OutStream = context.openfileoutput (filename, context.mode_append);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

public void savereadable (string filename, string content) throws exception{//ctrl+shift+y/x

FileOutputStream OutStream = context.openfileoutput (filename, context.mode_world_readable);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

public void savewriteable (string filename, string content) throws exception{//ctrl+shift+y/x

FileOutputStream OutStream = context.openfileoutput (filename, context.mode_world_writeable);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

public void Saverw (string filename, string content) throws exception{

FileOutputStream OutStream = context.openfileoutput (filename,

Context.mode_world_readable+ context.mode_world_writeable);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

public void SAVEPRW (string filename, string content) throws exception{

FileOutputStream OutStream = context.openfileoutput (filename,

Context.mode_world_readable+ context.mode_world_writeable+context.mode_append);

Outstream.write (Content.getbytes ());

Outstream.close ();

}

public string ReadFile (string filename) throws exception{

FileInputStream instream = context.openfileinput (filename);

byte[] data = ReadData (instream);//?????????????????

return new String (data);

}

Private byte[] ReadData (FileInputStream instream) throws exception{

Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();

byte[] buffer = new byte[1024];

int len = 0;

while (len = instream.read (buffer))! =-1) {

Outstream.write (buffer, 0, Len);

}

Outstream.close ();

Instream.close ();

return Outstream.tobytearray ();

}

}

  Last edited Dateactivity:package Com.jbridge.file;import Com.jbridge.event.filebuttononclickevent;import Android.app.activity;import Android.os.bundle;import Android.widget.button;public class DateActivity extends Activity {    /** Called when the activity is first created. */     @Override    &NB sp;public void OnCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);        setcontentview (r.layout.main);         Get all buttons         button buttonread = (button) This.findviewbyid (r.id.bt_read);   & nbsp    button buttonsave = (button) This.findviewbyid (r.id.bt_save);        //Add an event to the button & nbsp;       filebuttononclickevent filebtonclickeve = new Filebuttononclickevent (this);         buttonread.setonclicklistener (filebtonclickeve);     &nbsp  buttonsave.setonclicklistener (filebtonclickeve);    }}   Is the readability of our dateactivity.java very good? Of course! Continue to improve later. However, our fileservice does not use interfaces, which are developed using interfaces in Java EE, so that decoupling can be achieved. Because Android is a mobile operating system platform, if we open the analogy more, will occupy the system resources, resulting in slow system. Therefore, as far as possible to reduce the interface or class definition, but also to do as far as possible the readability of the program is better. Launch the simulator and deploy our program. Enter the filename and file contents and click Save. Where is the file saved on Android? We know that Android is implemented on Linux. So its root directory is "/" and our files are saved in the "/data/data/com.changcheng.file/files" directory. We can also open the File Explorer panel via the menu windows->show view->other...->android->file Explorer. It allows you to view the directory structure of Android: data: Applications, the files we save are in/data/data/packagename/files. SDcard: Now the mobile phone generally can plug in an SD card, this directory is sdcard directory. You need to register operation permissions in the master profile when manipulating this directory. System:android operating system files, we do not modify. We can export the file by clicking on the "Floppy left arrow" icon in the upper right corner of File explorer. 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. The created file is saved in the/data/data/<package Name>/files directory, and the second parameter of the Openfileoutput () method is used to specify the mode of operation, with four modes, respectively: Context.mode_private    =  0context.mode_append    =  32768context.mode_world_readable =  1Context.MODE _world_writeablE =  2context.mode_private: Is the default mode of operation, which means that the file is private data and can only be accessed by the application itself, in which the content of the write overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use Context.MODE_APPENDContext.MODE_APPEND: mode checks whether a file exists, appends content to the file, or creates a new file. This mode is also private data and can only be accessed by the app itself. Context.mode_world_readable and context.mode_world_writeable are used to control whether other apps have permission to read and write to the file. Mode_world_readable: Indicates that the current file can be read by another application; Mode_world_writeable: Indicates that the current file can be written by another application. You can use + to connect these permissions: If you want files to be read and written by other apps, you can pass in:  openfileoutput ("Itcast.txt", Context.mode_world_readable + Context.mode_ world_writeable); If you want the file to be read and written by another app and if it is appended, you can pass in:  openfileoutput ("Itcast.txt", Context.mode_world_readable + Context.mode_world_writeable+ Context.mode_append); Android has its own security model, and when the application (. apk) is installed, the system assigns him a userid, When the app is going to access other resources like files, it needs a userid match. By default, any file created by the app, Sharedpreferences, should be private (in/data/data/<package name>/files) and other programs cannot access it. Unless you specify context.mode_world_readable or context.mode_world_writeable at creation time, only such other programs can access them correctly. Like OutputStream, FileInputStream openfileinput (String name) can be called through the context object, To open the InputStream file named name in the current application's private file directory. If the file does not exist, it will be straightThe FileNotFoundException exception is thrown. In addition, when the application needs to read data from the project catalog assets/, you can open the file name as the name file by calling the context object to love your Inputstream:inputstream In=this.getassets.open (name);. The context object can also call the FileList () method to get a string array of all the file names in the private file directory, and call DeleteFile (string name) to delete the file named name. The activity also provides the Getcachedir () and Getfilesdir () methods: The Getcachedir () method is used to get/data/data/<package name>/ Cache directory (some temporary files can be dropped when the cache directory has been exhausted) the Getfilesdir () method is used to get the/data/data/<package name>/files directory other programs get the file path Method 1. Absolute path:/ Data/data/packagename/files/filename;2.context:   Context.getfilesdir () + "/filename"; Cache directory:/data/data/ Packagename/cache or Getcachedir ();    If the file is too large to be stored on the phone's file directory, it needs to be stored on sdcard. Use the activity of the Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general phone storage space is not very large, storage of small files is OK, if you want to store large files such as video, it is not feasible. For large files like video, we can store it in SDcard. What is sdcard for? You can think of it as a removable hard drive or USB stick.   using SDcard in the simulator, you need to create a SDcard card (certainly not a real sdcard, just the image file). Creating a sdcard can be created when eclipse creates the emulator, or it can be created using DOS commands, as follows: In the DOS window, enter the tools directory of the Android SDK installation path and create a 2G sdcard with the following command. File suffix can be arbitrarily taken, recommended to use. Img:mksdcard 2048M d:\androidtool\sdcard.img  access to SDcard in your program, you need to request permission to access SDcard. The permissions to add access to SDcard in Androidmanifest.xml are as follows:<!--Create and delete file permissions in SDcard--><uses-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/><!--Write Data permissions to SDcard--><uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/>  files stored in SDcard can be accessed by any app! SDcard directory:/sdcard/or Environment.getexternalstoragedirectory () before using the SDcard directory, Need to determine if there is sdcard:Environment.getExternalStorageState (). You need to register operation permissions in the master profile when manipulating this directory. If Environment.getexternalstoragestate () equals  environment.media_mounted   indicates sdcard exists and can read and write file Sdcarddir = Environment.getexternalstoragedirectory ();//obtainedFetch SDcard directory   equivalent to  file sdcarddir = new File ("/sdcard"); Get SDcard directory to the SDcard to store files, the program must first determine whether the phone is loaded with sdcard, and can read and write. Note: Access SDcard must have access to SDcard permissions in Androidmanifest.xml if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted)) {         File Sdcarddir = Environment.getexternalstoragedirectory ();//Get SDcard directory          File SaveFile = new file ( Sdcarddir, "Itcast.txt"); FileOutputStream OutStream = new FileOutputStream (saveFile); Outstream.write ("Write content". GetBytes ()); Outstream.close ();} The Environment.getexternalstoragestate () method is used to get the state of the sdcard, and if the phone is loaded with sdcard and can read and write, the method returns a state equal to Environment.media_ Mounted. The Environment.getexternalstoragedirectory () method is used to get the directory of the SDcard, of course, to get the SDcard directory, you can also write: file Sdcarddir = new file ("/sdcard "); Get sdcard directory file SaveFile = new file (Sdcarddir, "itcast.txt");  //the above two lines of code can be synthesized one sentence: file SaveFile = new file ("/sdcard/ Itcast.txt ");//The above two lines of code can be synthesized one sentence: file saveFile = new file (environment.getexternalstoragedirectory ()," ITCASt.txt "); FileOutputStream OutStream = new FileOutputStream (saveFile); Outstream.write ("Write content". GetBytes ()); Outstream.close ();  

Read and write Android files

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.