This article analyzes the reading and writing methods of Android programming files. Share it for your reference, as follows:
Android's file reading and writing are the same as JavaSE's file reading and writing, both using IO streams. Moreover, Android uses JavaSE IO streams. Let’s learn Android’s file reading and writing through an exercise.
1. Create an Android project
Project name:File
BuildTarget:Android2.2
Application name: File reading and writing
Package name:
Create Activity:DateActivity
Min SDK Version:8
File content:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Data saving</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文件成功</string> <string name="file_save_failed">save文件失败</string> <string name="file_read_failed">Read文件失败</string> </resources>
File content:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro 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: /> <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: /> <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: /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/bt_save" android:text="@string/button_file_read" android: android:layout_alignTop="@id/bt_save" /> </RelativeLayout> </LinearLayout>
Add java code
First, let’s add one to the project: it is actually the file operation in Java.
package ; import ; import ; import ; import ; import ; import ; public class FileService { private Context context; public FileService(Context context) { = context; } public void saveToSDCard(String filename, String content) throws Exception{ if(().equals(Environment.MEDIA_MOUNTED)){ File file = new File((), filename); FileOutputStream outStream = new FileOutputStream(file); (()); (); } } public void save(String filename, String content) throws Exception{ FileOutputStream outStream = (filename, Context.MODE_PRIVATE); (()); (); }
Then add to the project:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class FileButtonOnClickEvent implements OnClickListener { 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) { = activity; = new FileService(activity); } public void onClick(View v) { Button button = (Button) v; switch (()) { case .bt_save: // Get the file name EditText etFileNameS = (EditText) .findViewById(.et_file_name); String fileNameS = ().toString(); // Get the file content EditText etFileConS = (EditText) .findViewById(.et_file_content); String fileContentS = ().toString(); // Save try { (fileNameS, fileContentS); // Show a special effect information box in the window (, .file_save_success, Toast.LENGTH_LONG).show(); (TAG, "save file success!"); } catch (Exception e) { (, .file_save_failed, Toast.LENGTH_LONG).show(); (TAG, ()); } break; case .bt_read: // Get the file name EditText etFileNameR = (EditText) .findViewById(.et_file_name); String fileNameR = ().toString(); // Read the file try { String fielContentR = (fileNameR); EditText etFileConR = (EditText) .findViewById(.et_file_content); (fielContentR); (TAG, "read file success!"); } catch (Exception e) { (, .file_read_failed, Toast.LENGTH_LONG).show(); (TAG, ()); } break; default: break; } } } public void saveAppend(String filename, String content) throws Exception{// ctrl+shift+y / x FileOutputStream outStream = (filename, Context.MODE_APPEND); (()); (); } public void saveReadable(String filename, String content) throws Exception{// ctrl+shift+y / x FileOutputStream outStream = (filename, Context.MODE_WORLD_READABLE); (()); (); } public void saveWriteable(String filename, String content) throws Exception{// ctrl+shift+y / x FileOutputStream outStream = (filename, Context.MODE_WORLD_WRITEABLE); (()); (); } public void saveRW(String filename, String content) throws Exception{ FileOutputStream outStream = (filename, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE); (()); (); } public void savePRW(String filename, String content) throws Exception{ FileOutputStream outStream = (filename, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE+Context.MODE_APPEND); (()); (); } public String readFile(String filename) throws Exception{ FileInputStream inStream = (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 = (buffer))!= -1){ (buffer, 0, len); } (); (); return (); } }
Finally, our main activity: DateActivity
package ; import ; import ; import ; import ; public class DateActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(); // Get all buttons Button buttonRead = (Button) (.bt_read); Button buttonSave = (Button) (.bt_save); // Add events to the button FileButtonOnClickEvent fileBtOnClickEve = new FileButtonOnClickEvent(this); (fileBtOnClickEve); (fileBtOnClickEve); } }
Is our readability very good? certainly! Continue to improve in the future. However, our FileService does not use interfaces, and is developed in JavaEE, so that decoupling can be achieved. Since Android is a mobile operating system platform, if we open more classes, it will occupy system resources, resulting in slowing down the system. Therefore, try to minimize the definition of interfaces or classes, but also try to make the program readability as good as possible. So we can also merge DataActivity and FileButtonOnClickEvent.
Start the emulator and deploy our program. Enter the file name and file content and click Save. Where is the file saved in Android? We know that Android is based on Linux. So its root directory is "/", and our file is saved in the "/data/data/your package name.file/files" directory.
We can also open the File Explorer panel through the menu Windows->Show View->Other...->Android->File Explorer. Through it, you can view the Android directory structure:
data: Apply data, the file we save is in /data/data/packagename/files.
sdcard: Nowadays, mobile phones can usually plug in an SD card, and this directory is the SDCard directory. When operating this directory, you need to register operation permissions in the main configuration file.
system: Android operating system files, we do not modify them.
We can click the "Floppy Disk 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 and cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the /data/data/<package name>/files directory.
The second parameter of the openFileOutput() method is used to specify the operation mode. There are four modes, namely:
Context.MODE_PRIVATE = 0
Context.MODE_APPEND = 32768
Context.MODE_WORLD_READABLE = 1
Context.MODE_WORLD_WRITEABLE = 2
Context.MODE_PRIVATE: It is the default operation mode, which means 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. Context.MODE_APPEND can be used
Context.MODE_APPEND: The mode will check whether the file exists. If it exists, it will add content to the file, otherwise a new file will be 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 permission to read and write the file.
MODE_WORLD_READABLE: means that the current file can be read by other applications; MODE_WORLD_WRITEABLE: means that the current file can be written by other applications.
You can use + to connect these permissions:
If you want the file to be read and written by other applications, you can pass it in:
If you want the file to be read and written by other applications and have additional contents, you can pass it in:
Android has its own security model. When the application (.apk) is installed, the system will assign it a userid. When the application wants to access other resources such as files, the userid needs to match.. By default, any file created by the application, sharedpreferences, and databases should be private (located in /data/data/<package name>/files) and cannot be accessed by other programs. Unless Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE is specified at creation time, only in this way other programs can access it correctly.
Like OutputStream, you can call FileInputStream openFileInput(String name) through the Context object to open the InputStream file with the file name in the current application private file directory. If the file does not exist, a FileNotFoundException will be directly thrown.
In addition, when the application needs to read data from the project directory assets/, you can open the file name file by calling the Context object: InputStream in=(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 with the file name name.
Activity also provides getCacheDir() and getFilesDir() methods:
getCacheDir() method is used to obtain the /data/data/<package name>/cache directory (some temporary files can be placed in the cache directory and deleted after they are used up)
getFilesDir() method is used to get /data/data/<package name>/files directory
Methods for other programs to obtain file paths
1. Absolute path: /data/data/packagename/files/filename;
: ()+"/filename";
Cache directory: /data/data/packagename/Cache or getCacheDir();
If the file is too large, it cannot be stored in the file directory of the phone and needs to 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 storage space of the mobile phone is not very large, and storing some small files is OK. If you want to store large files like videos, it is not feasible. For large files like videos, we can store them in SDCard. What does SDCard do? You can think of it as a mobile hard drive or a USB drive.
To use SDCard in the emulator, you need to create an SDCard card first (of course not a real SDCard, just a mirror file). Creating SDCard can be created with Eclipse when creating an emulator, or it can be created using DOS commands, as follows:
Enter the tools directory of the Android SDK installation path in the Dos window, enter the following command to create a SDCard with a capacity of 2G, and the file suffix can be taken as you like. It is recommended to use .img:
mksdcard 2048M D:\AndroidTool\
To access SDCard in the program, you need to request permission to access SDCard.
Add the permissions to access SDCard in the following:
<!-- existSDCardCreate and delete files permissions --> <uses-permission android:name=".MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- PastSDCardWrite data permissions --> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/>
Files stored in sdcard can be accessed by any application!
SDCard directory: /sdcard/ or ()
Before using the SDCard directory, you need to determine whether there is sdcard: (). When operating this directory, you need to register operation permissions in the main configuration file.
If () is equal to Environment.MEDIA_MOUNTED means that sdcard exists and can be read and written
File sdCardDir = ();//Get the SDCard directory
Equivalent to File sdCardDir = new File("/sdcard"); //Get the SDCard directory
To store files in SDCard, the program must first determine whether the phone has SDCard and can read and write.
Note: Access to SDCard must be included in the permission to access SDCard
if(().equals(Environment.MEDIA_MOUNTED)){ File sdCardDir = ();//Get the SDCard directory File saveFile = new File(sdCardDir, ""); FileOutputStream outStream = new FileOutputStream(saveFile); ("Written content".getBytes()); (); }
The () method is used to obtain the status of the SDCard. If the phone has SDCard and can read and write, the status returned by the method is equal to Environment.MEDIA_MOUNTED.
The () method is used to obtain the directory of SDCard. Of course, to obtain the directory of SDCard, you can also write it like this:
File sdCardDir = new File("/sdcard"); //Get the SDCard directoryFile saveFile = new File(sdCardDir, ""); //The above two sentences can be combined into one sentence: File saveFile = new File("/sdcard/");//The above two sentences can be combined into one sentence: File saveFile = new File((), "");FileOutputStream outStream = new FileOutputStream(saveFile); ("Written content".getBytes()); ();
I hope this article will be helpful to everyone's Android programming design.