Basic android data storage-File (13)

Source: Internet
Author: User

I. Data storage File:

In android, you can create a file to save data on the storage device of the device or an external storage device. By default, files cannot be shared among different programs.

Context in android provides several methods for file operations.

1). openFileOutput (file name, operation mode ).

2). openFileInput (file name, operation mode ).

The first parameter is used to specify the file name, which cannot contain the path separator "/". If the file does not exist, android automatically creates it and stores the file in data/ /Files/directory. To View the File path here, you need to View the File path in File Explorer. In this case, choose Window> Show View> Other> Android> File Explorer.

The operation modes mentioned here are as follows:

1). Context. MODE_PRIVATE = 0

This is the default operation mode, which 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 newly written data to the original file, you can use Context. MODE_APPEND.

2). Context. MODE_WORLD_READABLE = 1

This mode indicates that the current file can be read by other applications.

3). Context. MODE_WORLD_WRITEABLE = 2

This mode indicates that the current file can be written by other applications.

4). Context. MODE_APPEND = 32768

This mode checks whether the file exists and adds content to the file if it exists. If it does not exist, the file is created and the content is added.

Note: openFileOutput (file name, Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE) is required to be readable by other applications ).


Example:

Layout file:

     
      
      
      
      
      
      
      
      
  
 


Service class (FileService. java ):

Public class FileService {private Context context; public FileService (Context context) {this. context = context;} public void fileOutput (String fileName, String fileContext) throws Exception {FileOutputStream fos = context. openFileOutput (fileName, Context. MODE_PRIVATE); fos. write (fileContext. getBytes (); fos. close ();} public String fileIntput (String fileName) throws Exception {byte [] data = null; System. ou T. println (fileName); FileInputStream FCM = context. openFileInput (fileName); // read the buffer data ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] B = new byte [1024]; int len = 0; while (-1! = (Len = Fi. read (B) {baos. write (B, 0, len);} data = baos. toByteArray (); return new String (data);} public void saveToSDCard (String fileName, String fileContext) throws Exception {File file File = new File (Environment. getExternalStorageDirectory (), fileName); // The openFileInput () method provided by the api cannot be used, because this method stores files in the storage location of the mobile phone. FileOutputStream out = new FileOutputStream (file); out. write (fileContext. getBytes (); out. close ();}}

Main Interface (FlieMain. java ):

Public class FlieMain extends Activity {private Button b1; private Button b2; private EditText e1; private EditText e2; private TextView t1; private Button b3; private FileService files; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_flie_main); b1 = (Button) findViewById (R. id. button1); b2 = (Button) findViewById (R. id. button2); B3 = (Button) findViewById (R. id. button3); files = new FileService (this); b1.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {e1 = (EditText) findViewById (R. id. editText1); e2 = (EditText) findViewById (R. id. editText2); String fileName = e1.getText (). toString (); String fileCon = e2.getText (). toString (); try {files. fileOutput (fileName, fileCon); toastPrint ("saved successfully");} catch (E Xception e) {toastPrint ("failed to save"); e. printStackTrace () ;}}); b3.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stube1 = (EditText) findViewById (R. id. editText1); e2 = (EditText) findViewById (R. id. editText2); String fileName = e1.getText (). toString (); String fileCon = e2.getText (). toString (); try {// determine whether the SD card can be read/written, and whether the SD card exists. If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {files. saveToSDCard (fileName, fileCon); toastPrint ("saved successfully");} else {toastPrint ("failed to save") ;}} catch (Exception e) {toastPrint ("failed to save"); e. printStackTrace () ;}});} public void toastPrint (String str) {Toast. makeText (this, str, Toast. LENGTH_SHORT ). show ();} public void onClick (View v) {try {String str = files. fileIntput (e1.getText (). toString (); toastPrint ("read succeeded" + str);} catch (Exception e) {// TODO Auto-generated catch blocktoastPrint ("read failed"); e. printStackTrace () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. flie_main, menu); return true ;}}

When you want to store data on the mobile phone SD card, you must add the permission in AndroidManifest. xml:

Create and delete files on the SD card

Write Data permission to SD card


Running effect:

Enter the file name in the first input box, and then enter the file content in the following input box. Click Save.

View the file location:

When you click the read button:

When we click Save to SD card:


Zookeeper

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.