Android learning diary 13-File storage of data storage

Source: Internet
Author: User

4. File: a traditional I/O Stream storage File. Activity provides the openFileOutput () method to output data to a File, the specific implementation process is the same as saving data to a file in the J2SE environment. The following example shows how to save, read, and save a file on the SD card. (1) save the file and copy code 1 public void save (String str) {2 3 try {4 FileOutputStream output = this. openFileOutput ("test.txt", Context. MODE_WORLD_READABLE); 5 output. write (str. getBytes (); 6 output. close (); 7 Toast. makeText (MainActivity. this, "Saved", Toast. LENGTH_LONG ). show (); 8} catch (IOException e) {9 // TODO: handle exception10} 11 12} the first parameter of the copy code openFileOutput () method is used to specify the file name, cannot contain path separator "/". If the file does not exist, Android It is automatically created. The created file is saved in the/data/<package name>/files directory, for example,/data/com. example. the second parameter of the filesave/files/test.txt openFileOutput () method is used to specify the operation mode. There are four modes: Context. ignore: the default operation mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the content written 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. 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. If you want the file to be read and written by other applications, You can input: openFileOutput ("test.txt", Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE); androidhas a set of security models. When the application (.apk) is installed, the system will assign a userid to the application. 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. (2) read file copy code 1 public String load () {2 String str = ""; 3 try {4 FileInputStream input = this. openFileInput ("test.txt"); 5 ByteArrayOutputStream byteOutput = new ByteArrayOutputStream (); 6 byte [] buffer = new byte [1024]; 7 8 int length =-1; 9 10 while (length = input. read (buffer ))! =-1) {11 byteOutput. write (buffer, 0, length); 12 13} 14 15 input. close (); 16 byteOutput. close (); 17 18 str = byteOutput. toString (); 19 20} catch (IOException e) {21 // TODO Auto-generated catch block22 e. printStackTrace (); 23} 24 25 return str; 26 27} copying code can only be accessed by applications that create a private file. If you want the file to be read and written by other applications, you can specify Context when creating a file. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE permission. Activity also provides the getCacheDir () and getFilesDir () Methods: getCacheDir () methods for obtaining/data/<package name>/cache directory getFilesDir () to obtain the/data/<package name>/files directory. Print the content read by the file: (3) create an SD card and use the openFileOutput () method of Activity to save the file. The file is stored in the mobile phone space. Generally, the mobile phone storage space is not very large, it is okay to store 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 drive or USB flash drive inserted into your mobile phone. Create a simulator SD card and set the file to readable. open the folder where you installed Android and find the tools Folder. copy the file to the path 2. set the default path of the command prompt to your copied Path 3. enter the following command (note space): mksdcard 256 m c: \ Users \ chendd \ Desktop \ sdcard. img m is the size of your SD card, followed by the path for creating the virtual SD card. Press enter to create the image file of the SD card and let the Android simulator know where the SD card is located. The command is as follows: dir C: \ Users \ chendd \ Desktop \ sdcard. img press enter again. 4. Set the simulator. Select "File" in "edit", and then browse your sdcard. img, and then edit AVD. Use DDMS to add it. In this case, the permissions of the sdcard under File Exprorer is changed to d --- rwxr-x. To access SDCard in a program, you need to apply for the permission to access SDCard. Add the permission to access SDCard in AndroidManifest. xml as follows: 1 <! -- Create and delete file permissions in SDCard --> 2 <uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/> 3 4 <! -- Write data permission to SDCard --> 5 <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE "/> (4) to store files on the SD card, the program must first determine whether the mobile phone has an SDCard, the Code 1 public void save_sd (String str) {2 3 File sdCardDir = Environment. getExternalStorageDirectory (); // get SDCard directory 4 5 File saveFile = new File (sdCardDir, "testsd.txt"); 6 7 FileOutputStream outStream; 8 try {9 outStream = new FileOutputStream (SaveFile); 10 outStream. write (str. getBytes (); 11 outStream. close (); 12} catch (IOException e) {13 // TODO Auto-generated catch block14 e. printStackTrace (); 15} 16 17} copy the code Environment. the getExternalStorageState () method is used to obtain the status of an SDCard. If an SDCard is installed on a mobile phone 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 "); // obtain the SDCard directory File saveFile = new File (sdCardDir, "test.txt"); // The first method is more flexible. // you can combine the above two sentences: file saveFile = new File ("/sdcard/a.txt"); FileOutputStream outStream = new FileOutputStream (saveFile); outStream. write ("test ". 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.