Android programming Documents Read and write examples of the detailed _android

Source: Internet
Author: User

In this paper, we analyze the methods of reading and writing the files of Android programming. Share to everyone for your reference, specific as follows:

The Android file reads and writes the same as the Javase file, using IO streaming. And Android uses the Javase IO stream, and here's an exercise to learn about Android's file reading and writing.

1. Create an Android project

Project Name:file
buildtarget:android2.2
Application Name: file read/write
Package Name:test.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" > FileName </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 "> read file failed </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" android:layout_height= "Wrap_content" an droid:text= "@string/file_name"/> <edittext android:layout_width= "Fill_parent" android:layout_height= Ontent "android:id=" @+id/et_file_name "/> <textview android:layout_width=" Fill_parent "android:layout_height = "Wrap_content" android:text= "@string/file_content"/> <edittext android:layout_width= "Fill_parent" Android: layout_height= "Wrap_content" android:minlines= "3" android:id= "@+id/et_file_content"/> <RelativeLayout, Andro Id:layout_width= "Fill_parent" android:layout_height= "wrap_content" > <button android:layout_width= "Wrap_con" Tent "android:layout_height=" WRAp_content "android:text=" @string/button_file_save "android:id=" @+id/bt_save "/> <button android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:layout_torightof= "@id/bt_save" Android:tex t= "@string/button_file_read" android:id= "@+id/bt_read" android:layout_aligntop= "@id/bt_save"/> </R

 Elativelayout> </LinearLayout>

Add Java code

First we add a Fileservice.java to the project: In fact, it is the file operation in Java.

 package test.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 {private context context; 
Public Fileservice {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.openfileou 
Tput (filename, context.mode_private); 
Outstream.write (Content.getbytes ()); 
Outstream.close (); }

And then add Filebuttononclickevent.java to the project:

Package test.event; 
Import TEST.FILE.R; 
Import Test.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 {private activity activity; 
 Through Fileservice read and write files private fileservice fileservice; 
 Label 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 filename 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); 
      Displays a special effects information 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 filename edittext Etfilenamer = (edittext) this.activity. Findviewbyid (R.id.et_file_ 
    name); 
    String Filenamer = Etfilenamer.gettext (). toString (); 
      Read the 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 ou 
Tstream = 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 outstr 
EAM = 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 outst 
Ream = 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.openfileou
Tput (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 ByteArrayOut 
Putstream (); 
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 ();

 }
}

And finally our Lord Activity:dateactivity.

Package test.file; 
Import test.event.FileButtonOnClickEvent; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.widget.Button; 
The public class Dateactivity extends activity {/** called the ' when ' is the ' The activity ' is a 
 -a-created 
 c void OnCreate (Bundle savedinstancestate) { 
  super.oncreate (savedinstancestate); 
  Setcontentview (r.layout.main); 
  Get All button buttons 
  buttonread = (button) This.findviewbyid (r.id.bt_read); 
  Button Buttonsave = (button) This.findviewbyid (r.id.bt_save); 
  Add an event to the button 
  filebuttononclickevent filebtonclickeve = new Filebuttononclickevent (this); 
  Buttonread.setonclicklistener (Filebtonclickeve); 
  Buttonsave.setonclicklistener (Filebtonclickeve); 
 }


Are our dateactivity.java very readable? Of course! Continue to improve later. But our fileservice does not use interfaces, which are developed using interfaces in Java EE, so decoupling can be achieved. Since Android is the mobile OS platform, if we set up more analogies, it will consume system resources, resulting in slow system. Therefore, as far as possible to reduce the definition of interfaces or classes, but also to do as much as possible to achieve the readability of the program better. So we can also combine dataactivity and filebuttononclickevent.

Start the simulator and deploy our program. Enter the filename and file contents and click Save. Where is the file stored on Android? We know that Android is implemented on Linux. So its root directory is "/", our files are saved in the "/data/data/your package name. File/files" directory.

We can also open the File Explorer panel by menu windows->show view->other...->android->file Explorer. It allows you to view the directory structure of Android:

Data: Applying the/data/data/packagename/files, we saved the files in the file.

SDcard: Now the mobile phone can generally insert an SD card, this directory is sdcard directory. When you manipulate this directory, you need to register the operation permissions in the main configuration file.

System:android operating system files, we do not modify.
We can export the file by clicking 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 files created are saved in the/data/data/<package name>/files directory,
The second parameter of the Openfileoutput () method is used to specify the mode of operation, with four modes, respectively:

Context.mode_private = 0
Context.mode_append = 32768
context.mode_world_readable = 1
Context.mode_world_writeable = 2

Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use the Context.mode_append
Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file. This pattern is also private data and can only be accessed by the application itself.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications 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 the + to connect these permissions:

If you want the file to be read and written by another application, you can pass in:

Copy Code code as follows:
Openfileoutput ("Itcast.txt", context.mode_world_readable + context.mode_world_writeable);

If you want the file to be read and written by other applications and append content, you can pass in:
Copy Code code as follows:
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, and when the application accesses other resources such as files, it needs userid matching . By default, any file created by the application, sharedpreferences, should be private (located in/data/data/<package name>/files) and not accessible by other programs. Unless context.mode_world_readable or context.mode_world_writeable are specified at the time of creation, only such other programs can access them correctly.

As with OutputStream, FileInputStream openfileinput (String name) can be invoked through the context object. To open the InputStream of a file with file name name in the current application private file directory. A FileNotFoundException exception is thrown directly if the file does not exist.

In addition, when an application needs to read out data from the project engineering directory, you can open the file name name file by calling the context object assets/love your Inputstream:inputstream in=this.getassets.open (name);.

The context object can also obtain a string array of all file names under the private file directory by calling the FileList () method, and call DeleteFile (String name) to delete the file named name.

The activity also provides Getcachedir () and Getfilesdir () methods:

The Getcachedir () method is used to get the/data/data/<package Name>/cache directory (some temporary files can be placed in the cache directory and deleted when they are exhausted)
The Getfilesdir () method is used to get the/data/data/<package name>/files directory

Methods for obtaining file paths from other programs

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 in the phone's file directory, it needs to be stored on the sdcard.

Use the activity of the Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general mobile phone storage space is not very large, storing small files also line, if you want to store such large files as video, it is not feasible. For large files like video, we can store them in SDcard. What's sdcard for? You can think of it as a removable hard disk or a USB drive.

To use SDcard in the emulator, you need to create a SDcard card (not really sdcard, just a mirrored file). Creating SDcard can be created when eclipse creates the emulator, or it can be created using a DOS command, as follows:

In the DOS window into the Android SDK installation path of the tools directory, enter the following command to create a capacity of 2G sdcard, file suffix can be arbitrarily taken, recommended. IMG:
Mksdcard 2048M D:\AndroidTool\sdcard.img

To access the SDcard in your program, you need to apply for access to SDcard permissions.

The right to join the access SDcard in Androidmanifest.xml is 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 application!

SDcard directory:/sdcard/or Environment.getexternalstoragedirectory ()
Before using the SDcard directory, you need to determine whether there are sdcard:Environment.getExternalStorageState (). When you manipulate this directory, you need to register the operation permissions in the main configuration file.

If Environment.getexternalstoragestate () equals environment.media_mounted indicating that sdcard exists and can read and write
File Sdcarddir = Environment.getexternalstoragedirectory ();//Get SDcard Directory
Equivalent to file Sdcarddir = new file ("/sdcard"); Get SDcard Directory

To store files to SDcard, the program must first determine whether the phone is fitted with sdcard and can read and write.

Note: Access to SDcard must be included in Androidmanifest.xml to access SDcard permissions

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 obtain the state of the sdcard, and if the phone has sdcard and can read and write, the state of the method return equals Environment.media_ Mounted.
Environment.getexternalstoragedirectory () method is used to get the directory of SDcard, of course, to obtain the SDcard directory, you can also write:

File Sdcarddir = new file ("/sdcard"); Gets the SDcard directory
file SaveFile = new file (Sdcarddir, "itcast.txt"); 
The above two code can synthesize one sentence: file SaveFile = new file ("/sdcard/itcast.txt");
The above two code can synthesize one sentence: file SaveFile = new file (Environment.getexternalstoragedirectory (), "Itcast.txt");
FileOutputStream OutStream = new FileOutputStream (savefile);
Outstream.write ("Write content". GetBytes ());
Outstream.close ();

I hope this article will help you with the Android program.

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.