Read and Write Android files

Source: Internet
Author: User
Android uses Io streams to read and write files in the same way as javase. In addition, Android uses the javase Io stream. Next we will use an exercise to learn how to read and write Android files.


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 content:

<? XML version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "app_name"> data storage </string> <string name = "file_name"> file name </string> <string name = "file_content"> File Content </string> <string name = "button_file_save"> Save </string> <string name = "button_file_read"> Read </string> <string name = "file_save_success"> Save the file </string> <string name = "file_save_failed"> failed to save the file </string> <string name = "file_read_failed"> failed to read the file </string> </resources>

Main. xml file content:
<? 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"> <! -- File name --> <textview Android: layout_width = "fill_parent" 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"/> <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 Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <button Android: layout_width = "wrap_content" 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: text = "@ string/button_file_read" Android: id = "@ + ID/bt_read" Android: layout_aligntop = "@ ID/bt_save"/> </relativelayout> </linearlayout>

Add Java code

First, we add a fileservice. Java to the project: Actually, we use the File Operations 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(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 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; // read and write the file private file through fileservice Service fileservice; // The tag Private Static final string tag = "filebuttononclickevent" for printing information; public filebuttononclickevent (activity) {This. activity = activity; this. fileservice = new fileservice (activity);} public void onclick (view v) {button = (button) V; Switch (button. GETID () {case R. id. bt_save: // get the file name edittext etfilenames = (edittext) This. activity. findviewbyid (R. id. et_fi Le_name); string filenames = etfilenames. gettext (). tostring (); // get the file content 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 effect information box toast in the window. maketext (this. activity, R. string. file_save_success, toast. length_long ). show (); log. I (TAG, "save file succ Ess! ");} 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 the file name 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 etfileco Nr = (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/xfileoutputstream outstream = context. openfileoutput (filename, context. mode_append); outstream. write (content. getbytes (); outstream. close ();} pub LIC void savereadable (string filename, string content) throws exception {// Ctrl + Shift + Y/xfileoutputstream 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/xfileoutputstream outstream = context. openfileoutput (filename, Conte XT. 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 {File Outputstream 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 (fileinput Stream 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 ();}}

Our main activity: dateactivity
Package test. file; import test. 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 public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // get all buttons button buttonread = (button) This. findviewbyid (R. id. bt_read); button buttonsave = (button) This. findviewbyid (R. id. bt_save); // Add the event filebuttononclickevent filebtonclickeve = new filebuttononclickevent (this) for the button; buttonread. setonclicklistener (filebtonclickeve); buttonsave. setonclicklistener (filebtonclickeve );}}


Is our dateactivity. Java readable? Of course! Continue to improve later. However, our fileservice does not use interfaces, and Java EE uses interfaces for development. This can achieve decoupling. Because Android is a mobile operating system platform, if we open many classes, it will occupy system resources, resulting in system slowdown. Therefore, try to reduce the definition of interfaces or classes, but also try to make the program readable. So we can also merge dataactivity and filebuttononclickevent. Start the simulator and deploy our program. Enter the file name and content, and click Save. Where is the file stored on Android? We know that android is implemented based on Linux. So its root directory is "/", and our files are saved in the "/data/your package name. File/Files" directory. You can also choose windows> show View> other...> Android> file explorer to open the file explorer panel. It allows you to view the directory structure of Android: Data: application data. The saved files are in/data/packagename/files. Sdcard: an SD card is usually available for mobile phones. This directory is the directory of sdcard. When operating this directory, you must register the operation permission in the main configuration file. System: file of the Android operating system. Do not modify it. Click the "floppy disk to left arrow" icon in the upper-right corner of file explorer to export the file. The first parameter of the openfileoutput () method is used to specify the file name. It cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the/data/<package name>/Files directory. The second parameter of openfileoutput () method is used to specify the operation mode. There are four modes: context. mode_private = 0context. mode_append = 32768context. mode_world_readable = 1context. mode_world_writeable = 2context. mode_private: the default operation mode. This 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_appendcontext.mode_append: the mode checks whether the file exists and appends the content to the file. Otherwise, a new file is created. This mode 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 the permission to read and write the file. Mode_world_readable: indicates that the current file can be read by other applications; mode_world_writeable: indicates that the current file can be written by other applications. You can use + to connect to these permissions: If you want the file to be read and written by other applications, 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 other applications, You can input: openfileoutput ("itcast.txt", context. mode_world_readable + context. mode_world_writeable + context.mode_append=androidhas a set of security models. When the application (.apk) is installed, the system will assign a userid to it. When the application wants to access other resources, such as files, userid matching is required. 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. Like outputstream, you can use the context object to call fileinputstream openfileinput (string name) to open the inputstream of the file named name in the private file directory of the current application. If the object does not exist, the filenotfoundexception exception is thrown. In addition, when the application needs to read data from the project directory assets/, you can call the context object to open the inputstream: inputstream in = This. getassets. open (name );. The context object can also obtain a string array composed of all file names in the private file directory by calling the filelist () method, and call deletefile (string name) to delete the file named name. Activity also provides the getcachedir () and getfilesdir () Methods: getcachedir () the getfilesdir () method is used to obtain the/data/<package name>/cache directory (some temporary files can be stored in the cache directory and deleted after they are used up () method 1. absolute path:/data/packagename/files/filename; 2. context: context. getfilesdir () + "/filename"; cache directory:/data/packagename/cache or getcachedir ();If the file is too large, it cannot be stored in the file directory of the mobile phone. It must be stored on the sdcard.Use the openfileoutput () method of activity to save files. The files are stored in the mobile phone space. Generally, the mobile phone storage space is not very large, and it is okay to store some small files, it is not feasible to store large files such as videos. For large files like videos, we can store them in sdcard. What does sdcard do? You can think of it as a mobile hard disk or a USB flash disk.
To use sdcard in the simulator, You need to first create an sdcard (of course, not a real sdcard, but an image file ). You can create sdcard along with the simulator created in eclipse, or you can use the doscommand to create it. In the DOS window, enter the tools directory of the android SDK installation path, run the following command to create an sdcard with a capacity of 2 GB. The file suffix can be obtained at will. IMG: mksdcard 2048 m d: \ androidtool \ sdcard. IMG
To access sdcard in a program, you need to apply for the permission to access sdcard. The permission to 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 permission 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 sdcard: environment. getexternalstoragestate () exists (). When operating this directory, you must register the operation permission in the main configuration file. If environment. getexternalstoragestate () is equal to environment. media_mounted indicates that sdcard exists and can be read and written to file sdcarddir = environment. getexternalstoragedirectory (); // get the sdcard directory is equivalent to file sdcarddir = new file ("/sdcard"); // get the sdcard directory and store the file to sdcard, the program must first determine whether the mobile phone has an sdcard and can read and write data. Note: The sdcard must be accessed in androidmanifest. if (environment. getexternalstoragestate (). equals (environment. media_mounted) {file sdcarddir = environment. getexternalstoragedirectory (); // get the sdcard directory file SaveFile = new file (sdcarddir, inititcast.txt "); fileoutputstream outstream = new fileoutputstream (SaveFile); outstream. write ("written content ". getbytes (); outstream. close ();} environment. use the getexternalstoragestate () method To obtain the status of the sdcard. If the mobile phone has an sdcard and can be read and written, the returned status is environment. media_mounted. Environment. the getexternalstoragedirectory () method is used to obtain the sdcard directory. To obtain the sdcard directory, you can also write: file sdcarddir = new file ("/sdcard "); // get the sdcard directory file SaveFile = new file (sdcarddir, "itcast.txt"); // you can combine the above two sentences: file SaveFile = new file ("/sdcard/itcast.txt"); // The code above can be combined into one sentence: file SaveFile = new file (environment. getexternalstoragedirectory (), effecitcast.txt "); fileoutputstream outstream = new fileoutputstream (SaveFile); outstream. write ("written content ". getbytes (); outstream. close ();

For more methods on file operations, refer to the article http://blog.csdn.net/aomandeshangxiao/article/details/6597302

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.