Reading and Writing Android files and reading and writing Android files

Source: Internet
Author: User

Reading and Writing Android files and reading and writing Android files

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: com. jbridge. 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"> the file is successfully saved. </string>

<String name = "file_save_failed"> An error occurred while saving the file. </string>

<String name = "file_read_failed"> An error occurred while reading 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"/> <! -- File content --> <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"/> <! -- Save and read buttons in 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" 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

We recommend that you use the MVC development mode for Android. Therefore, we recommend that you use the MVC design mode for Android application development. The MVC design pattern separates three layers, so as to ensure good decoupling.

First, 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 Activity is context. The context is the same as the context in other frameworks for some core operation 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 {

// Obtain other controls through activity

Private Activity;

// Read and write files through FileService

Private FileService fileService;

// Tag used to print 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 the file name

EditText etFileNameS = (EditText) this. activity

. FindViewById (R. id. et_file_name );

String fileNameS = etFileNameS. getText (). toString ();

// Obtain 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 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 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 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 ();

}

}

Finally, edit 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 public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // get all 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) ;}} our DateActivity. is 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. 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/com. changcheng. 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. when img accesses 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 ();

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.